I have this output results from database:
Array
(
[0] => stdClass Object
(
[name] => attr one
[attribute_id] => 1
[attribute_group] => group one
[attribute_group_id] => 1
)
[1] => stdClass Object
(
[name] => attr two
[attribute_id] => 2
[attribute_group] => group one
[attribute_group_id] => 1
)
[2] => stdClass Object
(
[name] => attr three
[attribute_id] => 3
[attribute_group] => group one
[attribute_group_id] => 1
)
[3] => stdClass Object
(
[name] => attr four
[attribute_id] => 4
[attribute_group] => group two
[attribute_group_id] => 2
)
)
now for json ouput:
foreach ($results as $result) {
$json[] = array(
'id' => $result->attribute_group_id,
'text' => $result->attribute_group,
'children' => [array(
'id' => $result->attribute_id,
'text' => $result->name,
)]
);
}
return json_encode($json);
output is:
[
{
"id":"1",
"text":"group one",
"children":[
{
"id":"1",
"text":"attr one"
}
]
},
{
"id":"1",
"text":"group one",
"children":[
{
"id":"2",
"text":"attr two"
}
]
},
{
"id":"1",
"text":"group one",
"children":[
{
"id":"3",
"text":"attr three"
}
]
},
{
"id":"2",
"text":"group two",
"children":[
{
"id":"4",
"text":"attr four"
}
]
}
]
But In Action I need to output grouped by attribute_group and listed in children like this:
[
{
"id":"1",
"text":"group one",
"children":[
{
"id":"1",
"text":"attr one"
},
"id":"2",
"text":"attr two"
},
{
"id":"3",
"text":"attr three"
}
]
},
{
"id":"2",
"text":"group two",
"children":[
{
"id":"4",
"text":"attr four"
}
]
}
]
how do can i create this json output?!
Instead of creating an array $json with an element for each attribute, you should gather each attribute directly by attribute_group_id.
In order to do that, the idea is to use the attribute_group_id as the key of your $json array ($json[$result->attribute_group_id]). If an entry already exists for $json[$result->attribute_group_id]['children'] then you just have to had the current children to this item. If not, you create the entry for the current attribute group ID with his information (id,text,children).
Finally you can return the $json without the key that we used for grouping the attributes using array_values (returns the values of an array without keys).
foreach ($results as $result) {
if(isset($json[$result->attribute_group_id]['children'])){
$json[$result->attribute_group_id]['children'][] = array(
'id' => $result->attribute_id,
'text' => $result->name,
);
}
else {
$json[$result->attribute_group_id] = array(
'id' => $result->attribute_group_id,
'text' => $result->attribute_group,
'children' => [array(
'id' => $result->attribute_id,
'text' => $result->name,
)]
);
}
}
return json_encode(array_values($json));
Result :
[
{
"id": "1",
"text": "group one",
"children": [
{
"id": "1",
"text": "attr one"
},
{
"id": "2",
"text": "attr two"
},
{
"id": "3",
"text": "attr three"
}
]
},
{
"id": "2",
"text": "group two",
"children": [
{
"id": "4",
"text": "attr four"
}
]
}
]
Related
I have the following structure:
{
"data": {
"array_1": [
{
"name": "Robert Kalani"
},
{
"name": "Balkan Boy",
}
],
"array_2": [
{
"name": "Pepe Dolan"
},
{
"name": "John Nolan",
}
],
"array_3": [
{
"name": "Phillip A. Luna",
},
{
"name": "Eugene Garcia"
}
]
}
}
I would like to sort each array by the name key in alpabetical order, not sure on how to do that, I've read about array_multisort but it seemed not to work. Would greatly appreciate some help
Here is the expected output
{
"data": {
"array_1": [
{
"name": "Balkan Boy",
},
{
"name": "Robert Kalani"
}
],
"array_2": [
{
"name": "John Nolan"
},
{
"name": "Pepe Dolan"
}
],
"array_3": [
{
"name": "Eugene Garcia"
},
{
"name": "Phillip A. Luna"
}
]
}
}
// Your JSON Data
$data = '{
"data": {
"array_1": [{ "name": "Robert Kalani" }, { "name": "Balkan Boy" }],
"array_2": [{ "name": "Pepe Dolan" }, { "name": "John Nolan" }],
"array_3": [{ "name": "Phillip A. Luna" }, { "name": "Eugene Garcia" }]
}
}
';
$result = [];
// Convert your JSON data to associative array
$array = json_decode($data, true)['data'];
function sort_by_name($a, $b)
{
return $a > $b;
}
foreach ($array as $item) {
uasort($item, "sort_by_name");
$result[] = $item;
}
echo "<pre>";
print_r($result);
Result:
Array
(
[0] => Array
(
[1] => Array
(
[name] => Balkan Boy
)
[0] => Array
(
[name] => Robert Kalani
)
)
[1] => Array
(
[1] => Array
(
[name] => John Nolan
)
[0] => Array
(
[name] => Pepe Dolan
)
)
[2] => Array
(
[1] => Array
(
[name] => Eugene Garcia
)
[0] => Array
(
[name] => Phillip A. Luna
)
)
)
I need to get an JSON structure as following:
{
"emails": [
{
"sender": "shihas#abc.com",
"unread_count": 2,
"items": [
{
"id": "89",
"email": "shihas#abc.com",
"read": "0",
},
{
"id": "32",
"email": "shihas#abc.com",
"read": "0",
}
]
},
{
"sender": "marias123#gmail.com",
"unread_count": 0,
"items": [
{
"id": "2",
"email": "marias123#gmail.com",
"read": "1",
}
]
},
{
"sender": "gutar4320#hotmail.com",
"unread_count": 1,
"items": [
{
"id": "1",
"email": "gutar4320#hotmail.com",
"read": "0",
}
]
}
]
}
Array($hire_email):
In the below array I need to group all the details based on the email. And also count the no. of unread messages(i.e read = 0).
Array
(
[0] => Array
(
[id] => 89
[email] => shihas#abc.com
[read] => 0
)
[1] => Array
(
[id] => 32
[email] => shihas#abc.com
[read] => 0
)
[2] => Array
(
[id] => 2
[email] => marias123#gmail.com
[read] => 1
)
[3] => Array
(
[id] => 1
[email] => gutar4320#hotmail.com
[read] => 0
)
)
The following is the code snippet used for maintaining the JSON structure.
foreach($hire_email as $val) {
if($val['read']==0){ $count++; }else{ $count = 0;}
$hire_group_email[$val['email']]['sender'] = $val['email'];
$hire_group_email[$val['email']]['unread_count'] = $count;
$hire_group_email[$val['email']]['items'][] = $val;
}
$output["emails"][] = $hire_group_email;
echo json_encode($output);
This should do the trick.
$hire_email =array(
array(
"id" => "89",
"email" => "shihas#abc.com",
"read" => "0"
),
array
(
"id" => "32",
"email" => "shihas#abc.com",
"read" => "0"
),
array
(
"id" => "2",
"email" => "marias123#gmail.com",
"read" => "1"
),
array
(
"id" => "1",
"email" => "gutar4320#hotmail.com",
"read" => "0"
)
);
$tmp = array();
foreach($hire_email as $arg)
{
$tmp[$arg['email']][] = $arg;
}
$output = array();
foreach($tmp as $type => $labels)
{
$count = 0;
foreach ($labels as $value) {
if($value['read']==0){ $count++; }else{ $count = 0;}
}
$output[] = array(
'sender' => $type,
'unread_count' => $count,
'items' => $labels
);
}
echo json_encode($output);
Try doing it like this, using: array_sum and array_column, the rest is just picking out the first items values.
$array = json_decode($json, true)['emails'];
$result = [];
foreach($array as $val) {
$result[] = [
'id' => $val['items'][0]['id'],
'email' => $val['items'][0]['email'],
'read' => array_sum(array_column($val['items'], 'read'))
];
}
$output["emails"] = $result;
echo json_encode($output, JSON_PRETTY_PRINT);
Result:
{
"emails": [
{
"id": "89",
"email": "shihas#abc.com",
"read": 0
},
{
"id": "2",
"email": "marias123#gmail.com",
"read": 1
},
{
"id": "1",
"email": "gutar4320#hotmail.com",
"read": 0
}
]
}
https://3v4l.org/hi7qm
And if you want it as shown ;p (my mistake, misread it):
Loop over each item, then loop over the items and use that to build the output.
$array = json_decode($json, true)['emails'];
$result = [];
foreach($array as $val) {
foreach ($val['items'] as $item) {
$result[] = [
'id' => $item['id'],
'email' => $item['email'],
'read' => array_sum(array_column($val['items'], 'read'))
];
}
}
$output["emails"] = $result;
echo json_encode($output, JSON_PRETTY_PRINT);
Result:
{
"emails": [
{
"id": "89",
"email": "shihas#abc.com",
"read": 0
},
{
"id": "32",
"email": "shihas#abc.com",
"read": 0
},
{
"id": "2",
"email": "marias123#gmail.com",
"read": 1
},
{
"id": "1",
"email": "gutar4320#hotmail.com",
"read": 0
}
]
}
https://3v4l.org/eU95A
I have an array like below:
Array ( [0] => Array ( [SI] => 1
[name] => Nick
[location] => Russia
[year] => 2011 )
[1] => Array ( [SI] => 8
[name] => Mike
[location] => Russia
[year] => 2011 )
[2] => Array ( [SI] => 2
[name] => Tom
[location] => Russia
[year] => 2010 )
[3] => Array ( [SI] => 6
[name] => Duke
[location] => Russia
[year] => 2010 ) )
Current JSON format:
{
"name": "Amalians",
"img": "https:\/\/dl.dropboxusercontent.com\/u\/19954023\/marvel_force_chart_img\/marvel.png",
"children": [
{
"name": "2011"
},
{
"children": [
{
"SI": "1"
}
]
},
{
"children": [
{
"name": "Nick"
}
]
},
{
"children": [
{
"location": "Russia"
}
]
},
{
"name": "2011"
},
{
"children": [
{
"SI": "8"
}
]
},
{
"children": [
{
"name": "Mike"
}
]
},
{
"children": [
{
"location": "Russia"
}
]
},
{
"name": "2010"
},
{
"children": [
{
"SI": "2"
}
]
},
{
"children": [
{
"name": "Tom"
}
]
},
{
"children": [
{
"location": "Russia"
}
]
},
{
"name": "2010"
},
{
"children": [
{
"SI": "6"
}
]
},
{
"children": [
{
"name": "Duke"
}
]
},
{
"children": [
{
"location": "Russia"
}
]
}
]
}
Desired JSON format:
{
"name": "marvel",
"img": "https://dl.dropboxusercontent.com/u/19954023/marvel_force_chart_img/marvel.png",
"children": [
{
"name": "2011",
"children": [
{
"SI": "1",
"name": "Nick",
"location": "Russia"
},
{
"SI": "8",
"name": "Mike",
"location": "Russia"
}
]
},
{
"name": "2010",
"children": [
{
"SI": "2",
"name": "Tom",
"location": "Russia"
},
{
"SI": "6",
"name": "Duke",
"location": "Russia"
}
]
}
]
}
CODE:
$data['name'] = "Amalians";
$data['img'] = "https://dl.dropboxusercontent.com/u/19954023/marvel_force_chart_img/marvel.png";
foreach($people as $row)
{
$data['children'][]['name'] = $row['year'];
$data['children'][]['children'][]['SI'] = $row['SI'];
$data['children'][]['children'][]['name'] = $row['name'];
$data['children'][]['children'][]['location'] = $row['location'];
}
echo "<pre>";
echo json_encode($data,JSON_PRETTY_PRINT);
echo "</pre>"; exit();
NOTE: $people is the array defined above.
Please kindly help me to do this. I have been working on this for last two days and till this moment I couldn't find any solution. Thanks
i guess the simplest way is to group your data
$arrData = [
[
"SI" => 1,
"name" => "Nick",
"location" => "Russia",
"year" => 2011
],
[
"SI" => 2,
"name" => "Mike",
"location" => "Russia",
"year" => 2011
],
[
"SI" => 3,
"name" => "Tom",
"location" => "Russia",
"year" => 2010
],
[
"SI" => 4,
"name" => "Duke",
"location" => "Russia",
"year" => 2010
],
];
$arrGroupedData = [];
foreach($arrData AS $row)
{
$arrGroupedData[$row['year']][] = [ "SI" => $row['SI'], "name" => $row['name'], "location" => $row['location']];
}
$arrGroupFormattedData = [];
foreach($arrGroupedData AS $key => $arrGroup)
{
$arrGroupFormattedData[] = ["name" => $key, "children" => $arrGroup];
}
$data = [
"name" => "Amalians",
"img" => "https://dl.dropboxusercontent.com/u/19954023/marvel_force_chart_img/marvel.png",
"children" => $arrGroupFormattedData
];
echo json_encode($data,JSON_PRETTY_PRINT);
You can try this:
Here you need to group the array by key year.
$array = array();
foreach ($people as $val) {
$array[$val['year']][] = $val;
}
$data['name'] = "Amalians";
$data['img'] = "https://dl.dropboxusercontent.com/u/19954023/marvel_force_chart_img/marvel.png";
$i = 0;
foreach ($array as $key => $value) {
foreach ($value as $key2 => $value2) {
$data['children'][$i]['name'] = $value2['year'];
$data['children'][$i]['children'][$key2]['SI'] = $value2['SI'];
$data['children'][$i]['children'][$key2]['name'] = $value2['name'];
$data['children'][$i]['children'][$key2]['location'] = $value2['location'];
}
$i++;
}
echo "<pre>";
echo json_encode($data, JSON_PRETTY_PRINT);
echo "</pre>";
exit();
<?php
$array = Array(Array( "SI" => 1,
"name" => Nick,
"location" => Russia,
"year" => 2011),
Array ( "SI" => 8,
"name" => Mike ,
"location" => Russia ,
"year" => 2011),
Array ( "SI" => 2,
"name" => Tom,
"location" => Russia,
"year" => 2010 ),
Array ( "SI" => 6,
"name" => Duke,
"location" => Russia ,
"year" => 2010 ) );
$json_final['child'] = array();
$temp = array();
foreach($array as $arr)
{
$flag=0;
if(!empty($json_final['child']))
{
foreach($json_final['child'] as $name_data)
{
if($name_data['name'] == $arr['year'])
{
$flag=1;
array_push($name_data['child_sub'],array("SI"=>$arr['SI'],"name"=>$arr['name'],"location"=>$arr['location']));
array_push($temp, $name_data);
}
}
}
if($flag == 0)
{
array_push($json_final['child'],array("name"=>$arr['year'],"child_sub"=>array(array("SI"=>$arr['SI'],"name"=>$arr['name'],"location"=>$arr['location']))));
}
}
$json_final['child'] = $temp;
//print_r($json_final);
echo json_encode($json_final,true)
?>
Here i have one array(first array) inside i have one more array(second array), now i want to display only first image from second array(galleryImages) , how can do this. i tried but i am not able to get the results
print_r($response);
Array
(
[0] => stdClass Object
(
[gallery_id] => 2
[title] => Annual Day 2017
[description] =>
[galleryImages] => ["1.jpg","2.jpg","3.jpg","4.jpg"]
[reg_on] => 2017-05-17 01:55:12
[created_by] => rajeshdash123#gmail.com
[school_id] => 2
[status] => 0
)
[1] => stdClass Object
(
[gallery_id] => 3
[title] => Sports Day
[description] =>
[galleryImages] => ["1.jpg","2.jpg","3.jpg"]
[reg_on] => 2017-05-17 01:55:36
[created_by] => rajeshdash123#gmail.com
[school_id] => 2
[status] => 0
)
)
Expected Results
{
"status": "Success",
"data": [
{
"gallery_id": "2",
"title": "Annual Day 2017",
"description": "",
"galleryImagesCount": 4,
"gallery":"1.jpg"
},
{
"gallery_id": "3",
"title": "Sports Day 2017",
"description": "",
"galleryImagesCount": 4,
"gallery":"1.jpg"
}
],
}
I tried like this but is i am not getting the exact results
$images = array();
foreach ($response as $key => $value)
{
$img['gallery_id'] = $value->gallery_id;
$img['title'] = $value->title;
$img['description'] = $value->description;
$img['galleryImagesCount'] = count(json_decode($value->galleryImages,true));
$img['gallery'] = json_decode($value->galleryImages,true);
array_push($images,$img);
}
$return=array('status'=>"Success",'Images'=>$images);
echo json_encode($return);
Getting Results
{
"status": "Success",
"Images": [
{
"gallery_id": "2",
"title": "Annual Day 2017",
"description": "",
"galleryImagesCount": 4,
"gallery": [
"d17ac9d0aeb6435eaa294e0d69d4cc8f.jpg",
"a91945e0cf55379f51cf5faef10d7a4a.jpg",
"2d1501045ddbb3ccc238e70f9af05027.jpg",
"071c3b5f969bed1d1e2ee4b6531e4444.jpg"
]
},
{
"gallery_id": "3",
"title": "Sports Day",
"description": "",
"galleryImagesCount": 4,
"gallery": [
"f0ba574fd46a01ff5a41855a97c710ca.jpg",
"1d10802f1b74e660117f36bd6dd0aa26.jpg",
"e705fb66f767a1b914200ca8d3cae700.jpg",
"3d5d8828331e13d3decc94021a64e5ca.jpg"
]
}
]
}
Here what happening means gallery is coming an array , for me don't want array i need first image only, please check my expected results, update the answer
Updated expected results
{
"status": "Success",
"Images": [
{
"gallery_id": "2",
"title": "Annual Day 2017",
"description": "",
"galleryImagesCount": 4,
"gallery": [
{
"galleryimage": "1.jpg"
},
{
"galleryimage": "2.jpg"
}
]
},
{
"gallery_id": "3",
"title": "Sports Day",
"description": "",
"galleryImagesCount": 4,
"gallery": [
{
"galleryimage": "1.jpg"
},
{
"galleryimage": "2.jpg"
}
]
}
]
}
Instead of [galleryImages] => ["1.jpg","2.jpg","3.jpg"], use for loop to iterate through galleryImages.
Create an associative array with key =>value pair like [galleryImages] => ["galleryimage1" => "1.jpg", "galleryimage2" => "2.jpg", "galleryimage3" => "3.jpg"].
While json_decode you will get intended output.
My changes and explanations are in the code block:
Code: (Demo)
// assumed that previous line was something like $response=json_decode($json);
$response=[
(object)[
'gallery_id'=>2,
'title'=>'Annual Day 2017',
'description'=>'',
'galleryImages'=>["1.jpg","2.jpg","3.jpg","4.jpg"],
'reg_on'=>'2017-05-17 01:55:12',
'created_by'=>'rajeshdash123#gmail.com',
'school_id'=>2,
'status'=>0
],
(object)[
'gallery_id'=>3,
'title'=>'Sports Day',
'description'=>'',
'galleryImages'=>["1.jpg","2.jpg","3.jpg"],
'reg_on'=>'2017-05-17 01:55:36',
'created_by'=>'rajeshdash123#gmail.com',
'school_id'=>2,
'status'=>0
]
];
foreach ($response as $value){ // removed $key=> because it was unnecessary
$img['gallery_id'] = $value->gallery_id;
$img['title'] = $value->title;
$img['description'] = $value->description;
$img['galleryImagesCount'] = count($value->galleryImages); // removed json_decode()
$img['gallery'] = $value->galleryImages[0]; // removed json_decode and added [0] to access first
$images[]=$img; // swapped push() call with identical function-less "push"
}
if(isset($images)){ // added this condition to ensure there was something to return
$return=array('status'=>"Success",'Images'=>$images);
//var_export($return);
echo json_encode($return);
}else{
// enter some sort of error message / default behavior
}
Output:
{"status":"Success","Images":[{"gallery_id":2,"title":"Annual Day 2017","description":"","galleryImagesCount":4,"gallery":"1.jpg"},{"gallery_id":3,"title":"Sports Day","description":"","galleryImagesCount":3,"gallery":"1.jpg"}]}
Document :
{
"version": "1.0.0",
"actor": {
"objectType": "Agent",
"name": "Test user",
"account": {
"homePage": "http://testing.com/",
"name": "67"
}
},
"verb": {
"id": "http://adlnet.gov/expapi/verbs/completed",
"display": {
"en-US": "completed"
}
},
"object": {
"objectType": "Activity",
"id": "http://localhost/action?id=cji",
"definition": {
"type": "http://adlnet.gov/expapi/activities/lesson",
"name": {
"en-US": "ps3"
},
"description": {
"en-US": "ps3"
}
}
},
"timestamp": "2016-10-25T11:21:25.917Z",
"context": {
"extensions": {
"http://localhost/eventinfo": {
"sessionId": "1477393533327",
"starttm": "1477394351210",
"eventtm": "1477394485917",
"course": "cji"
}
},
"contextActivities": {
"parent": [
{
"objectType": "Activity",
"id": "http://localhost/id=cji"
}
]
}
},
"result": {
"duration": "PT2M14.71S",
"score": {
"raw": 6,
"max": 21
}
},
"authority": {
"objectType": "Agent",
"name": "New Client",
"mbox": "mailto:hello#lhd.net"
},
"stored": "2016-10-25T11:20:29.666700+00:00",
"id": "c7039783-371f-4f59-a665-65a9d09a2b7f"
}
We've got this PHP + MongoDB aggregation query:
$condition = array(
array(
'$match' => array(
'client_id' => $CFG->mongo_clientid,
'statement.actor.account.name' => array('$in'=> array('67','192','213')),
'statement.verb.id' => 'http://adlnet.gov/expapi/verbs/completed',
'statement.object.id' => 'http://localhost/action?id=cji'
)),
array(
'$group' => array(
'_id' => '$statement.actor.account.name' ,
//'totalpoints' =>array( '$sum' => array('$last' => '$statement.result.score.raw'))
'laststatement' => array('$last' => '$statement.result.score.raw'),
//'sumtest' => array('$add' => ['$laststatement'])
)
)
);
$cursor = $collection->aggregate($condition);
echo "";
print_r($cursor);
echo "";
which returns this result:
Array
(
[result] => Array
(
[0] => Array
(
[_id] => 192
[laststatement] => MongoInt64 Object
(
[value] => 4
)
)
[1] => Array
(
[_id] => 67
[laststatement] => MongoInt64 Object
(
[value] => 6
)
)
)
[ok] => 1
)
How do we sum [laststatement].[value] of these individual array elements in MongoDB aggregation query?
[laststatement] => MongoInt64 Object
(
[value] => values goes here
)
Also, how do we use $last and $sum together in MongoDB aggregation query?
In my result there are 2 raw scores(last statement) for 2 different id (192,67). I want to sum this scores like 4 + 6 = 10 for all multiple id's but want only the last scores from the last statement. I am unable to use $last and $sum on the line. Please check
Looks like all you want is a single group. So the grouping id should be null. You may want to add a sort if you care for what last record should be. Not tested.
array(
'$group' => array(
'_id' => null ,
'totalpoints' => array( '$sum' => '$statement.result.score.raw')
'laststatement' => array('$last' => '$statement.result.score.raw')
)
)
Here is the mongo shell version.
aggregate([
{
$match :{
"actor.account.name":{$in:["67","192","213"]},
"verb.id":{$eq:"http://adlnet.gov/expapi/verbs/completed"},
"object.id":{$eq:"http://localhost/action?id=cji"}
}
},
{
$group: {
"_id": null,
"totalpoints" : {$sum:"$result.score.raw"},
"laststatement" :{$last:"$result.score.raw"}
}
}
])
Output:
{ "_id" : null, "totalpoints" : 10, "laststatement" : 4 }
Update Changed to include the sum for the last statement from each group. The first grouping is by actor name and returns the last statement from each group. The second grouping sums all the last statement.
aggregate([{
$match: {
"actor.account.name": {
$in: ["67", "192", "213"]
},
"verb.id": {
$eq: "http://adlnet.gov/expapi/verbs/completed"
},
"object.id": {
$eq: "http://localhost/action?id=cji"
}
}
}, {
$group: {
"_id": "$actor.account.name",
"laststatement": {
$last: "$result.score.raw"
}
}
}, {
$group: {
"_id": null,
"totalpoints": {
$sum: "$laststatement"
},
}
}])