I am getting json data from an api endpoint, I would like to add a key value to an array that I get. This is my function:
$magazines = Magazine::all();
foreach ($magazines as $magazine) {
$result = file_get_contents('http://customer.pages.com/?customer=' . $magazine->visio_link_prefix . '&action=latest');
$issues[] = json_decode($result, true);
}
foreach ($issues as $issue) {
Issue::create([
''
'title' => $issue['papers'][0]['title'],
'date' => $issue['papers'][0]['date'],
'foldername' => $issue['papers'][0]['foldername'],
'thumb' => $issue['papers'][0]['thumb'],
'thumbmedium' => $issue['papers'][0]['thumbmedium'],
]);
}
The array that I get from the endpoint looks like this:
array:24 [▼
0 => array:1 [▼
"papers" => array:1 [▼
0 => array:11 [▼
"title" => "News- 2014-10-22"
"date" => "2014-10-22"
"expires" => ""
"catalog" => 24
"foldername" => "News"
"folder" => 4965
"pages" => 132
"sectionstarts" => "1"
"sectioncount" => 1
"thumb" => "www.customer.pages.com/news/24/teasers/small.jpg"
"thumb_medium" => "www.customer.pages.com/news/24/teasers/medium.jpg"
]
]
]
1 => array:1 [▶]
2 => array:1 [▶]
3 => array:1 [▶]
4 => array:1 [▶]
5 => array:1 [▶]
6 => array:1 [▶]
7 => array:1 [▶]
8 => array:1 [▶]
9 => array:1 [▶]
10 => array:1 [▶]
11 => array:1 [▶]
12 => array:1 [▶]
13 => array:1 [▶]
14 => array:1 [▶]
15 => array:1 [▶]
16 => array:1 [▶]
17 => array:1 [▶]
18 => array:1 [▶]
19 => array:1 [▶]
20 => array:1 [▶]
21 => array:1 [▶]
22 => array:1 [▶]
23 => array:1 [▶]
]
So, in my foreach loop I would like to add a key value pair 'magazineId' => $magazine->id to each of the above 'papers' arrays. So that later I can use $issue['papers'][0]['magazineId'] to get the value of the $magazine->id. Not sure how to do that?
This correction to yoiur code should do the trick:
foreach ($magazines as $magazine) {
$result = file_get_contents('http://customer.pages.com/?customer=' . $magazine->visio_link_prefix . '&action=latest');
$issue = json_decode($result, true);
foreach($issue['papers'] as $paperKey => $paper) {
$issue['papers'][$paperKey]['magazineId'] = $magazine->id;
}
$issues[] = $issue;
}
foreach ($issues as $issue) {
Issue::create([
'magazineId' => $issue['papers'][0]['magazineId'],
'title' => $issue['papers'][0]['title'],
'date' => $issue['papers'][0]['date'],
'foldername' => $issue['papers'][0]['foldername'],
'thumb' => $issue['papers'][0]['thumb'],
'thumbmedium' => $issue['papers'][0]['thumbmedium'],
]);
}
And the second version where you have only one magazineId key for a single issue:
foreach ($magazines as $magazine) {
$result = file_get_contents('http://customer.pages.com/?customer=' . $magazine->visio_link_prefix . '&action=latest');
$issue = json_decode($result, true);
$issue['magazineId'] = $magazine->id;
$issues[] = $issue;
}
Could you please try code below? In first foreach I added an array to $issue.
$magazines = Magazine::all();
foreach ($magazines as $magazine) {
$result = file_get_contents('http://customer.pages.com/?customer=' . $magazine->visio_link_prefix . '&action=latest');
$issues[] = array('magazine_id' => $magazine->id, 'result' => json_decode($result, true);
}
foreach ($issues as $issue) {
Issue::create([
'magazine_id' => $issue['magazine_id'],
'title' => $issue['result']['papers'][0]['title'],
'date' => $issue['result']['papers'][0]['date'],
'foldername' => $issue['result']['papers'][0]['foldername'],
'thumb' => $issue['result']['papers'][0]['thumb'],
'thumbmedium' => $issue['result']['papers'][0]['thumbmedium'],
]);
}
Related
I'm consuming an API with Guzzle via laravel and storing the response into a database.
I've been successful in storing the "ratings" part of the JSON response. But now I'd like to add "meta" - "extractDate".
What do I need to change to get this to work?
Below is the JSON API response I'm working from and part of the controller I'm using to save into my database.
Using laravel 7.0
**JSON from API**
{
"ratings": [
{
"ratingId": 12,
"ratingName": "5",
"ratingKey": "fhrs_5_en-gb",
"ratingKeyName": "5",
"schemeTypeId": 1,
"links": [
{
"rel": "self",
"href": "http://api.ratings.food.gov.uk/ratings/12"
}
]
}
],
"meta": {
"dataSource": "API",
"extractDate": "2020-06-29T21:24:43.820107+01:00",
"itemCount": 11,
"returncode": "OK",
"totalCount": 11,
"totalPages": 1,
"pageSize": 11,
"pageNumber": 1
}
}
**controller snippet**
$client = $this->client();
$request = $client->request('GET', 'https://api.ratings.food.gov.uk/ratings');
$ratings = json_decode($request->getBody()->getContents(), true);
collect($ratings['ratings'])
->each(function($rating, $key) {
Rating::updateOrCreate([
'ratingId' => $rating['ratingId'],
'ratingName' => $rating['ratingName'],
'ratingKey' => $rating['ratingKey'],
'ratingKeyName' => $rating['ratingKeyName'],
'schemeTypeId' => $rating['schemeTypeId'],
'extractDate' => $rating['extractDate']
]);
});
Edit -- Additional Info
Correct me if I'm wrong but at the moment I think the collection is only able to save the contents of the "Ratings" object. I've tried to remove the object from the collect line and amend each line as:
'ratingId' => $rating['rating']['ratingId'],
'extractDate' => $rating['meta']['extractDate']
But I get 'Undefined index: rating'
DD of $ratings
array:3 [▼
"ratings" => array:11 [▼
0 => array:6 [▼
"ratingId" => 12
"ratingName" => "5"
"ratingKey" => "fhrs_5_en-gb"
"ratingKeyName" => "5"
"schemeTypeId" => 1
"links" => array:1 [▶]
]
1 => array:6 [▶]
2 => array:6 [▶]
3 => array:6 [▶]
4 => array:6 [▶]
5 => array:6 [▶]
6 => array:6 [▶]
7 => array:6 [▶]
8 => array:6 [▶]
9 => array:6 [▶]
10 => array:6 [▶]
]
"meta" => array:8 [▼
"dataSource" => "API"
"extractDate" => "2020-06-29T22:56:04.250649+01:00"
"itemCount" => 11
"returncode" => "OK"
"totalCount" => 11
"totalPages" => 1
"pageSize" => 11
"pageNumber" => 1
]
"links" => array:1 [▶]
]
You don't have any data structured like this:
'ratingId' => $rating['rating']['ratingId']
There is no key in your that is 'rating'.
You have
'ratingId' => $ratings['ratings'][$idx]['rating_id']
I think what you want is this:
collect($ratings['ratings'])
->each(function($rating, $key) use ($ratings) {
Rating::updateOrCreate([
'ratingId' => $rating['ratingId'],
'ratingName' => $rating['ratingName'],
'ratingKey' => $rating['ratingKey'],
'ratingKeyName' => $rating['ratingKeyName'],
'schemeTypeId' => $rating['schemeTypeId'],
'extractDate' => $ratings['meta']['extractDate']
]);
});
My original comment is based on your question :)
I have a table that I want to export via excel. I use the method toArray(); and still I get the result as object. Here is my sample code
$items = \DB::table('users')
->join('finances', 'users.id','=','finances.user_id')
->join('schoolyears', 'users.school_id','=','schoolyears.school_id')
->select('users.name','users.phone','users.section_id', 'users.student_school_id','finances.amount','finances.description','schoolyears.name as syear','finances.date')
->where('finances.date', '=' ,(\DB::raw("(select max(`date`) from finances f where finances.user_id=f.user_id)")))
->where('users.role','=','4' )
->where('users.school_id','=', $sid)
->get()->toArray();
// dd($items);
} else {
return redirect('home')->with('error', 'Invalid access');
}
\Excel::create($this->page_title . 's', function ($excel) use ($items) {
$excel->sheet($this->page_title . 's', function ($sheet) use ($items) {
$sheet->fromArray($items);
});
The result I get when i dd($items)
array:2 [▼
0 => {#558 ▼
+"name": "Annamarie Morar"
+"phone": "(0997) 212-7919"
+"section_id": null
+"student_school_id": "50"
+"amount": "500"
+"description": "New Pays"
+"syear": "SY-2019-2020"
+"date": "2019-11-14"
}
1 => {#561 ▶}
]
What i want is like this so that i can export it as an excel file
array:9 [▼
0 => array:10 [▼
"FirstName" => "Madelynn"
"LastName" => "Stokes"
"Gender" => "female"
"Birthday" => "2013-10-09"
"Address" => "78A/40 Goodwin Meadow, Poblacion, Iloilo City 1333 Nueva Ecija"
"PhoneNo" => "+63 (971) 659-8143"
"Parent" => "Deondre Stokes"
"SchoolID" => "521"
"RFID" => "173"
"Section" => null
]
1 => array:10 [▶]
2 => array:10 [▶]
3 => array:10 [▶]
4 => array:10 [▶]
5 => array:10 [▶]
6 => array:10 [▶]
7 => array:10 [▶]
8 => array:10 [▶]
]
You could convert each object to an array by transforming the Collection then turning the Collection into an array if you had to:
$items = DB::table(...)->.....->get()->transform(function ($item) {
return (array) $item;
})->toArray();
Laravel 6.x Docs - Collections - Methods - transform
When saving in an array the prices and ids of a product, with this code...
foreach($resource->group->tabs as $tab) {
foreach($tab->articles as $article)
{
$prices_and_ids[] = array(
$article->article_erp_id => array(
'price_pvp' => $article->price_pvp,
'price_promotion' => $article->price_promotion,
)
);
}
}
The result of $prices_and_ids with this code is an object with the keys numbered:
array:10 [▼
0 => array:1 [▼
3140 => array:2 [▼
"price_pvp" => 6.5
"price_promotion" => 5.53
]
]
1 => array:1 [▼
3141 => array:2 [▼
"price_pvp" => 7.5
"price_promotion" => 6.37
]
]
2 ... ... ...
The result I want is that the article ids are the keys of the array.
I want this:
array:10 [▼
3140 => array:1 [▼
"price_pvp" => 6.5
"price_promotion" => 5.53
]
3141 => array:1 [▼
"price_pvp" => 7.5
"price_promotion" => 6.37
] ... ... ...
the problem with your code is your adding it in another array do this
$prices_and_ids[$article->article_erp_id]
instead of
$prices_and_ids[]
foreach($resource->group->tabs as $tab) {
foreach($tab->articles as $article)
{
$prices_and_ids[$article->article_erp_id] = array(
$article->article_erp_id => array(
'price_pvp' => $article->price_pvp,
'price_promotion' => $article->price_promotion,
)
);
}
}
Instead of $prices_and_ids[] you should use $prices_and_ids[$article->article_erp_id]
foreach($resource->group->tabs as $tab) {
foreach($tab->articles as $article)
{
$prices_and_ids[$article->article_erp_id] array(
'price_pvp' => $article->price_pvp,
'price_promotion' => $article->price_promotion,
);
}
}
Change your foreach body as following code
$prices_and_ids[$article->article_erp_id] = array(
'price_pvp' => $article->price_pvp,
'price_promotion' => $article->price_promotion,
);
I'm trying to store values in an array structured like this:
{"parent":
{"class":"Green","user_name":"Nitish","user_loc":"Delhi","user_id":1,"user_blockclass":null,
"child":[
{"class":"Green","user_name":null,"user_loc":null,"user_id":1,"user_blockclass":"fst",
"child":[
{"class":"Green","user_name":"pandey","user_loc":"sdgfsjd","user_id":6,"user_blockclass":"fst"},
{"class":"Green","user_name":"chaku","user_loc":"sdgjs","user_id":7,"user_blockclass":"snd"},
{"class":"Green","user_name":"iks","user_loc":"sjkdfhkjs","user_id":8,"user_blockclass":"trd"},
{"class":"Green","user_name":"yash","user_loc":"hfksjdhfk","user_id":9,"user_blockclass":"frt"},
{"class":"Green","user_name":"joshi","user_loc":"dsfh","user_id":10,"user_blockclass":"fth"}
]},
{"class":"Green","user_name":null,"user_loc":null,"user_id":1,"user_blockclass":"snd",
"child":[
{"class":"Green","user_name":"pandey","user_loc":"sdgfsjd","user_id":6,"user_blockclass":"fst"},
{"class":"Green","user_name":"chaku","user_loc":"sdgjs","user_id":7,"user_blockclass":"snd"},
{"class":"Green","user_name":"iks","user_loc":"sjkdfhkjs","user_id":8,"user_blockclass":"trd"},
{"class":"Green","user_name":"yash","user_loc":"hfksjdhfk","user_id":9,"user_blockclass":"frt"},
{"class":"Green","user_name":"joshi","user_loc":"dsfh","user_id":10,"user_blockclass":"fth"}
]},
]
}
}
I'm trying to place this in two different array and the joining them, but it is not getting the approrpiate result, I've used a variable which iterates to store the different values, if I don't use iteration it overlaps the values and only shows the last stored values. Following is my code:
$blockclass = ['fst', 'snd', 'trd', 'frt', 'fth'];
$i = 0;
$children = $user->relations()->wherePlanId($selectplan)->get();
foreach($children as $ch)
{
$j = 0;
$subuserinfo = [];
$parent_id = $ch->pivot->child;
$subuser = User::find($ch->pivot->child);
$subuserinfo['class'] = "Green";
$subuserinfo['user_name'] = $ch->name;
$subuserinfo['user_loc'] = $ch->city;
$subuserinfo['user_id'] = $ch->id;
$subuserinfo['user_blockclass'] = $blockclass[$i];
if($subuser){
$subchildren = $subuser->relations()->wherePlanId($selectplan)->get();
foreach($subchildren as $subchild)
{
$subsubuser = User::find($subchild->pivot->child);
$subsubuserinfo['class'] = "Green";
$subsubuserinfo['user_name'] = $subsubuser->name;
$subsubuserinfo['user_loc'] = $subsubuser->city;
$subsubuserinfo['user_id'] = $subsubuser->id;
$subsubuserinfo['user_blockclass'] = $blockclass[$j];
$subuserinfo['child'][$i][$j++] = $subsubuserinfo;
}
}
else
{
$subuserinfo['child'][$i][$j++] = NULL;
}
$userinfo['child'][$i++] = $subuserinfo;
}
$tree = $userinfo;
dd($tree);
Currently the data structure which I'm getting is in following format:
array:6 [▼
"class" => "Green"
"user_name" => "Nitish"
"user_loc" => "Delhi"
"user_id" => 1
"user_blockclass" => null
"child" => array:4 [▼
0 => array:6 [▼
"class" => "Green"
"user_name" => null
"user_loc" => null
"user_id" => 1
"user_blockclass" => "fst"
"child" => array:1 [▼
0 => array:5 [▼
0 => array:5 [▼
"class" => "Green"
"user_name" => "pandey"
"user_loc" => "sdgfsjd"
"user_id" => 6
"user_blockclass" => "fst"
]
1 => array:5 [▼
"class" => "Green"
"user_name" => "chaku"
"user_loc" => "sdgjs"
"user_id" => 7
"user_blockclass" => "snd"
]
2 => array:5 [▼
"class" => "Green"
"user_name" => "iks"
"user_loc" => "sjkdfhkjs"
"user_id" => 8
"user_blockclass" => "trd"
]
]
]
]
1 => array:6 [▶]
2 => array:6 [▶]
3 => array:6 [▶]
I'm not able to fetch the data in this format, also after this I want to place the data to be used as json format. Help me out.
I thinkyou should replace all $subuserinfo['child'][$i][$j++] = $subsubuserinfo; with $subuserinfo['child'][$j++] = $subsubuserinfo;
I see you are using Laravel? If you use return response()->json($tree); it will print JSON.
If you also want the parent in front of the JSON you can use this:
return response()->json(['parent' => $tree]);
So I have a piece of code that I have been fighting with for a while now.
Here is the code that I have
<?php
namespace App\Http\Controllers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Requests\SearchRequest;
use Vinelab\Http\Client as HttpClient;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class SearchResults extends Controller
{
public function index()
{
return view('results.search-results');
}
public function store(Requests\SearchRequest $request)
{
$searchPhrase = $request->input('search');
$client = new HttpClient;
$response = $client->get('https://www.reddit.com/search.json?q='. urldecode($searchPhrase) .'');
$response = collect($response->json());
$responseDecode = json_decode($response, true);
$SearchResultsArray = $responseDecode;
dd($SearchResultsArray);
}
}
And this returns a nested array that looks like this
array:2 [▼
"kind" => "Listing"
"data" => array:5 [▼
"facets" => []
"modhash" => ""
"children" => array:25 [▼
0 => array:2 [▼
"kind" => "t3"
"data" => array:52 [▶]
]
1 => array:2 [▶]
2 => array:2 [▶]
3 => array:2 [▶]
4 => array:2 [▶]
5 => array:2 [▶]
6 => array:2 [▶]
]
"after" => "t3_38lgh9"
"before" => null
]
]
I am trying to access the title attribute that is inside each of these
1 => array:2 [▶]
2 => array:2 [▶]
3 => array:2 [▶]
4 => array:2 [▶]
5 => array:2 [▶]
6 => array:2 [▶]
7 => array:2 [▶]
I want to parse them to an array that I can send to a Laravel View.
Every time I try to acccess this I get undefined index or offset and I am at a loss as to how to go about this.
Can anybody assist me in finding a solution to this problem?
Edit ---------------------
I am now using this and it is working perfectly
$allData=[];
$counter = 1;
foreach ($posts as $post) {
//foreach post get the data and store it in a database
$allData[$counter]['title']= $post['data']['title'];
$sentiment = SentimentAnalysis::decision($allData[$counter]['title']);
$allData[$counter]['created']= $post['data']['created'];
RedditPosts::create([
'title' => $allData[$counter]['title'],
'created' => date($allData[$counter]['created']),
'sentiment' => $sentiment,
'search_identifier' => $search_id,
'search_phrase' => $searchPhrase
]);
$counter ++;
}
Basically you would need three foreach in your case to achieve the nested arrays like this
foreach($SearchResultsArray as $ThreeLevelArray){
foreach($ThreeLevelArray as $TwoLevelArray) {
foreach($TwoLevelArray as $OneevelArray) {
//your here son :)
}
}
}
$allData=[];
$counter = 1;
foreach ($posts as $post) {
//foreach post get the data and store it in a database
$allData[$counter]['title']= $post['data']['title'];
$sentiment = SentimentAnalysis::decision($allData[$counter]['title']);
$allData[$counter]['created']= $post['data']['created'];
RedditPosts::create([
'title' => $allData[$counter]['title'],
'created' => date($allData[$counter]['created']),
'sentiment' => $sentiment,
'search_identifier' => $search_id,
'search_phrase' => $searchPhrase
]);
$counter ++;
}