Get the values from a nested JSON array in PHP Laravel - php

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 ++;
}

Related

Laravel Object of class stdClass could not be converted to string. Still object when using toArray();

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

Store array keys in variable with foreach loop PHP

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,
);

How to store the quantity in the $regTypes array?

I want to have an array with the info about each registration type associated with a registration. For example if for the registration with id "1" the user selected two registration types of type "General" and one of the type "Plus" the $regTypes array should have this content with 2 item:
'registrationTypes' => [
[
'name' => 'general',
'price' => '5',
'quantity' => '2'
],
[
'name' => 'plus',
'price' => '10',
'quantity' => '1'
]
]
The registration_types table have the name and the price. So I have this query to get some info about a registration in a conference.
$registration = Registration
::with('conference', 'Conference.registrationTypes')->where('id', 1)->first();
And then I have this code to create the array with the necessary info:
$regTypes = [];
foreach($registration->conference->registrationTypes as $key=>$registrationType){
$regTypes [
'regType' => [
'name' => $registration->conference->registrationTypes[$key]['name'],
'price' => $registration->conference->registrationTypes[$key]['price']
]
];
}
My doubt is how to also store the quantity in the $regTypes array. Because the quantity is not stored in the database.
Maybe to get the quantity is necessary to do antoher query. With this code below:
$registrationTypeDetails = Registration::with('participants:id,registration_type_id,registration_id')->find($regID);
//dd($registrationTypeDetails);
$type_counts = [];
foreach ($registrationTypeDetails->participants as $p) {
$name = $p->registration_type->name;
if (!isset($type_counts[$name])) {
$type_counts[$name] = 0;
}
$type_counts[$name]++;
}
dump($type_counts);
The $type_counts shows the quantity of each registration type associated with the registration:
array:2 [▼
"general" => 2
"plus" => 1
]
Do you know how to use this $type_counts content to store the quantity properly in the $regTypes array?
To directly answer your question (IE not change the controller code, just "use this $type_counts content to store the quantity properly in the $regTypes array"), I'm hopeful this should work for you:
$regTypes = [];
foreach($registration->conference->registrationTypes as $key=>$registrationType){
$typeName = $registration->conference->registrationTypes[$key]['name'];
$regTypes [
'regType' => [
'name' => $typeName,
'price' => $registration->conference->registrationTypes[$key]['price'],
'quantity' => $type_counts[$typeName]
]
];
}
Basically just pulling the count from the $type_counts array based on the name of the Registration Type being the key that you added in the foreach ($registrationTypeDetails->participants as $p) loop.
Depending upon what you are after, it might be easier just to loop on the registration types, rather than go through $registration->conference->registrationTypes. This way you don't have duplicates. But that assumes you don't want duplicates :)
I hope this code useful for you .If you need the number of participants in any type, you can use the following code:
$registration = Registration::with('conference','Conference.registrationTypes','Conference.registrationTypes.participants')
->where('id',$regID)->first();
$result=$registration->conference->registrationTypes->each(function ($item, $key) use($registration) {
$item['try_count']=$item->participants->count();
});
dd($result->toArray());
I added the try_count variable to the final result:
array:2 [▼
0 => array:6 [▼
"id" => 1
"name" => "general"
"price" => 0
"conference_id" => 1
"try_count" => 8
"participants" => array:8 [▼
0 => array:5 [▶]
1 => array:5 [▶]
2 => array:5 [▶]
3 => array:5 [▶]
4 => array:5 [▶]
5 => array:5 [▶]
6 => array:5 [▶]
7 => array:5 [▶]
]
]
1 => array:6 [▼
"id" => 2
"name" => "plus"
"price" => 1
"conference_id" => 1
"try_count" => 5
"participants" => array:5 [▼
0 => array:5 [▶]
1 => array:5 [▶]
2 => array:5 [▶]
3 => array:5 [▶]
4 => array:5 [▶]
]
]
]

How to store values in array then use it as json

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]);

Php add a key value to associative array in foreach loop

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'],
]);
}

Categories