Group json nested object in php - php

I have a json response like below:
$response ='[
{
"userSummaries": [
{
"id": "9910",
"status": "Active",
"name": "Jhon"
}
]
},
{
"userSummaries": [
{
"id": "8754",
"status": "Active",
"name": "Jane"
}
]
}
]';
and I would like to group this by userSummaries with this php code:
$myArr = json_decode($response, true);
$result_arr = [];
array_walk($myArr,function($v,$k) use (&$result_arr){
$result_arr[key($v)] = $v[key($v)];
});
echo json_encode($result_arr);
and the response only return one data:
{"userSummaries":[{"id":"8754","status":"Active","name":"Jane"}]}
Is it possible to get the output response like this?:
{"userSummaries":[{"id":"9910","status":"Active","name":"Jhon"}, {"id":"8754","status":"Active","name":"Jane"}, ]}
Tried over the net but I did not found the solutions
here my script for this: https://3v4l.org/tVkK5
also tried this:
$class_array = array();
foreach ($myArr as $sa) {
$class_array[$sa['userSummaries']][] = array('name' => $sa['name']);
}
but return:
Notice: Undefined index: name in /in/hvSFC on line 28
Warning: Illegal offset type in /in/hvSFC on line 28
Notice: Undefined index: name in /in/hvSFC on line 28
Warning: Illegal offset type in /in/hvSFC on line 28
[]
need help

You were close. You just needed to reference the key and first of userSummaries in each loop, instead of working with the whole...
$myArr = json_decode($response, true);
$result_arr = ["userSummaries"=>[]];
foreach($myArr as $user) {
$result_arr["userSummaries"][] = $user['userSummaries'][0];
}
echo json_encode($result_arr);
Results in:
{"userSummaries":[
{"id":"9910","status":"Active","name":"Jhon"},
{"id":"8754","status":"Active","name":"Jane"}
]}
If you foresee that userSummaries in each will have multiple users themselves... then this would work:
$response ='[
{
"userSummaries": [
{
"id": "9910",
"status": "Active",
"name": "Jhon"
}
]
},
{
"userSummaries": [
{
"id": "8754",
"status": "Active",
"name": "Jane"
},
{
"id": "5421",
"status": "Active",
"name": "Bob"
}
]
}
]';
$myArr = json_decode($response, true);
$result_arr = ["userSummaries"=>[]];
foreach($myArr as $usergroup) {
foreach($usergroup['userSummaries'] as $user) {
$result_arr["userSummaries"][] = $user;
}
}
echo json_encode($result_arr);
Results in:
{"userSummaries":[
{"id":"9910","status":"Active","name":"Jhon"},
{"id":"8754","status":"Active","name":"Jane"},
{"id":"5421","status":"Active","name":"Bob"}
]}

Related

Add data to JSON child array

This is my JSON file(database.json):
{
"doctors": [
{
"ID": "ahmadakhavan",
"pass": "1234",
"name": "Ahmad Akhavan",
"profilePic": "address",
},
{
"ID": "akramparand",
"pass": "1234",
"name": "Akram Parand",
"profilePic": "address",
}
],
"games": [
{
"ID": "shuttlefuel_1",
"locked": "0",
"logo": "gameLogo",
},
{
"ID": "birthdaycake",
"locked": "0",
"logo": "gameLogo",
}
],
"users": [
{
"ID": "alirezapir",
"prescribes": [
{
"doctorName": "doctor1",
"done": "yes",
"gameId": "wordschain"
},
{
"doctorName": "doctor2",
"done": "no",
"gameId": "numberlab"
}
],
"profilePic": "address"
},
{
"ID": "amirdibaei",
"pass": "1234",
"profilePic": "address"
}
]
}
I want to add a child under prescribes array for a specific ID.
Below is what I have done in my PHP code to do this:
<?php
$username = $_REQUEST['name'];
$data = $_REQUEST['data'];
//Load the file
$contents = file_get_contents('./database.json');
$arraydata = json_decode($data,true);
//Decode the JSON data into a PHP array.
$contentsDecoded = json_decode($contents, true );
foreach($contentsDecoded['users'] as $item){
if($item['ID'] == $username){
if(!isset($item['prescribes'])){
$item['prescribes'] = Array();
}
array_push($item['prescribes'],$arraydata);
$json = json_encode($contentsDecoded, JSON_UNESCAPED_UNICODE );
file_put_contents('./database.json', $json);
exit('1');
exit;
}
}
exit('0');
exit;
?>
If I echo $item['prescribes'] after the line array_push($item['prescribes'],$arraydata); I see data added to it, but the original file (database.json) won't show new added data.
(meaning that this new data is not added to $contentsDecoded)
You have to change foreach() code like below:-
foreach($contentsDecoded['users'] as &$item){ //& used as call by reference
if($item['ID'] == $username){
$item['prescribes'][] = $arraydata; //assign new value directly
$json = json_encode($contentsDecoded, JSON_UNESCAPED_UNICODE );
file_put_contents('./database.json', $json);
exit;
}
}
Change your foreach to change the $contentsDecoded array:
foreach($contentsDecoded['users'] as $key => $item){
if($item['ID'] == $username){
if(!isset($item['prescribes'])){
$contentsDecoded['users'][$key]['prescribes'] = Array();
}
array_push($contentsDecoded['users'][$key]['prescribes'],$arraydata);
$json = json_encode($contentsDecoded, JSON_UNESCAPED_UNICODE );
file_put_contents('./database.json', $json);
exit('1');
exit;
}
}

Accessing Data in Array - Non-Object Error PHP

I'm populating an array like this:
$POarray = array();
foreach($orders as $order)
{
$total = OrderItems::where('OrderID', $order->OrderID)->sum('TotalPrice') * (1 + $LRmarkup);
$arraydata = array(
'Name' => $order->OrderNumber,
'Total' => $total);
$POarray[] = $arraydata;
}
This results in the contents of the $POarray variable being:
[
{
"Name": "DS-BS-18102654",
"Total": 241.4655
},
{
"Name": "test test",
"Total": "600.00"
}
]
I am attempting to access this data like this:
$purchase1name = $POarray[0]->Name;
$purchase1total = $POarray[0]->Total;
And I am getting this error:
"Trying to get property of non-object"
Shouldn't this work?
Thank you for taking the time to respond.
$POarray is not an object.
Try:
$purchase1name = $POarray[0]['Name'];
$purchase1total = $POarray[0]['Total'];
You need to do this way after decoding it using json_decode(),
<?php
$key='[
{
"Name": "DS-BS-18102654",
"Total": 241.4655
},
{
"Name": "test test",
"Total": "600.00"
}
]';
$POarray = json_decode($key);
echo $POarray[0]->Name;
echo $POarray[0]->Total;
?>
DEMO: https://3v4l.org/JvCam
You can also use this.
array_get($POarray[0], 'Name');
array_get($POarray[0], 'Total');
For more information: https://laravel.com/docs/5.7/helpers

var_dump and print_r displays different results - PHP

I have a string (JSON type), i wanted to convert it to PHP Array.
{
"action":"putEntity",
"dataPacket":{
"entity":[
{
"name":"product",
"data":[
{ }
]
}
]
}
}
I did following to do so,
$array = json_decode(json_encode($data), True);
When i do var_dump($array); it displays:
string(1578) "{ "action": "putEntity", "dataPacket": { "entity": [{ "name": "product", "data": [{ }] }] } }"
But when i do, print_r($array); it displays:
{
"action": "putEntity",
"dataPacket":{
"entity":[
{
"name": "product",
"data":[{}]
}
]
}
}
Issue is when i try to print $array['dataPacket']; it throws error illegal string offset 'dataPacket'
why var_dump is showing it as String? please help.
$array = json_decode(json_encode($data), True);
Should be
$array = json_decode($data, true);

Can't deal with foreach levels with JSON decoding

I've been dealing with this problem around 5 hours, so I think that's time to ask here.
I'm retrieving data using Facebook Graph API and using JSON decoding to put it all together on a PHP.
Here's FB Graph:
{
"feed": {
"data": [
{
"message": "A file.",
"id": "831407506978898_831408573645458",
"attachments": {
"data": [
{
"target": {
"id": "1041214692589250",
"url": "https://www.facebook.com/download/A-PDF-FILE.pdf"
},
"title": "Clase 01 - Vías de administración.pdf",
"type": "file_upload",
"url": "https://www.facebook.com/download/A-PDF-FILE.pdf"
}
]
}
},
{
"picture": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg",
"message": "A photo.",
"id": "831407506978898_831408496978799",
"attachments": {
"data": [
{
"description": "A photo.",
"media": {
"image": {
"height": 540,
"src": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg",
"width": 720
}
},
"target": {
"id": "10207838160017396",
"url": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg"
},
"type": "photo",
"url": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg"
}
]
}
},
{
"picture": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg",
"id": "831407506978898_831408450312137",
"attachments": {
"data": [
{
"media": {
"image": {
"height": 540,
"src": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg",
"width": 720
}
},
"target": {
"id": "10207838168217601",
"url": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg"
},
"type": "photo",
"url": "https://fbcdn-photos-c-a.akamaihd.net/A-PHOTO.jpg"
}
]
}
},
{
"message": "TEST",
"id": "831407506978898_831407576978891"
},
{
"id": "831407506978898_831407516978897"
}
],
"paging": {
"previous": "https://graph.facebook.com/...alotofjunk"
}
},
"id": "0000000000000"
}
And my PHP is the following one:
<?php
header('Content-Type: text/html; charset=utf-8');
$limit = 60; // The number of posts fetched
$access_token='TOKEN NUMBER';
$group_id = 'GROUPNUMBER';
$url1 = 'https://graph.facebook.com/'.$group_id.'?access_token='.$access_token;
$des = json_decode(file_get_contents($url1)) ;
$url2 = "https://graph.facebook.com/{$group_id}/feed?access_token={$access_token}";
$data = json_decode(file_get_contents($url2));
?>
<?
$counter = 0;
foreach($data->data as $d) {
if($counter==$limit)
break;
?>
<? $themessage = (isset($d->message) ? $d->message : false); ?>
<? print $themessage ?>
<? $thepicture = (isset($d->picture) ? $d->picture : false); ?>
<? print "<img src=\"$thepicture\">" ?>
<!--THE PROBLEM IS FROM HERE.... -->
<?
$counter = 0;
foreach($d->attachments->data as $d2) {
if($counter==$limit)
break;
?>
<? $attachments = (isset($d2->url) ? $d2->url : false); ?>
<? print $attachments ?>
<?
}
?>
<!-- ...TO HERE -->
<?
$counter++;
}
?>
I get a perfect output of $themessage and $thepicture, but I with $attachments I receive the following errors:
Notice: Undefined property: stdClass::$attachments in...
Notice: Trying to get property of non-object in...
Warning: Invalid argument supplied for foreach() in...
I've already read this: Trouble with Facebook multi-level json php foreach loop, but no luck.
How can I fix this?. Thanks a lot!
You need to be careful when you're chaining objects - especially in loops. One empty object will bring down the whole show. Try this:
$counter = 0;
if( isset( $d->attachments ) )
{
foreach( $d->attachments->data as $d2 )
{
....
}
}
Notice: Undefined property: stdClass::$attachments in...
Notice: Trying to get property of non-object in...
Warning: Invalid argument supplied for foreach() in...
You're getting this error becoz you're missing feed object in your first loop
HereDEMO
Replace
foreach($data->data as $d) {
if($counter==$limit)
break;
?>
With
foreach($data->feed->data as $d) {
if($counter==$limit)
break;
?>
Your JSON is in this format paste your JSON here JSON Format Viewer and check it
I tried your code i'm able to get url printed HereDEMO
$data="Your JSON Here"
foreach($data->feed->data as $d) {
$themessage = (isset($d->message) ? $d->message : false);
print("\n".$themessage);
$thepicture = (isset($d->picture) ? $d->picture : false);
print("\n<img src='$thepicture'>");
foreach($d->attachments->data as $d2) {
$attachments = (isset($d2->url) ? $d2->url : false);
print("\n".$attachments);
}
}
Side Note: you're initailising $counter = 0; twice once inside loop
and outside the loop its bad Even for $attachment, Its my opinion after looking your code for first time whatever you're reason be behind it

json object is bahaving wrongly

I am test-running a web application
where in json is required. I have the following json
structure:
{
"Articles": [
{
"Article": {
"ID": 111,
"title": "Idiot",
"author": "Moron",
"pubDate": "11/2/14",
"summary": "bla bla bla"
},
"Article": {
"ID": 222,
"title": "wisdom",
"author": "wise one",
"pubDate": "11/2/15",
"summary": "ha ha ha"
}
}
]
}
I then decided to check if a matching ID exits before adding
any record. To this effect, I wrote a method, encased it within
a JSon class as follows:
public function ID_Exists($ID){
$file = file_get_contents($this->FileName, true);
$data = json_decode($file, false); //get json in array string format
foreach($data as $child){
foreach($child as $item){
if($item->ID == $ID){
echo 'Exists';
}else{
echo 'Non Existent';
}
}
}
}
I test-ran it like:
$Obj = new JSon('file.json'); //knows what to do
if($Obj->ID_Exists(111)){
//ok ! no problem
}else{
////no problem
}
Here's the output I got:
Undefined property: stdClass::$ID in
C:\Server\wamp\www\Oweb\libs\dmanager.php on line 635
What am I doing wrong? I don't want to use the array
format of json_decode().
Your JSON structure is impossible. Articles is an array which contains a single object which contains the key Article twice - this cannot work.
Your structure needs to be:
{
"Articles": [
{
"ID": 111,
...
},
{
"ID": 222,
...
}
]
}
Which you can traverse using:
$data = json_decode($json);
foreach ($data->Articles as $article) {
if ($article->ID == ..) ..
}

Categories