Reputation: 3769
I'm trying to sort the a specific node inside a json object and return it in a PHP function that looks like this.
{
"2007":{
"number-xx" : "5",
"number-aa" : "30",
"number-ef" : "2",
"number-sa" : "-10",
"number-ab" : "28",
},
"2008":{
"number-xx" : "-1",
"number-aa" : "0.5",
"number-ef" : "23",
"number-sa" : "55",
"number-ab" : "43",
}
}
I want sort to each node under the "year" descending order and return it back in a function
{
"number-xx" : "-1",
"number-aa" : "0.5",
"number-ef" : "23",
"number-sa" : "55",
"number-ab" : "43",
}
PHP code to return the json
private function buildQuilt($fund_type){
$path = storage_path() . "/data.json";
$json = json_decode(file_get_contents($path), true);
//Do sort here
foreach($json as $key => &$arr) {
natsort($arr);
$arr = array_reverse($arr);
}//Seems to be breaking full object?
return $json;
}
I want to return the entire data.json object sorted but my solution above seems to only return on year node.
Upvotes: 1
Views: 113
Reputation: 8288
you may simply use array_map
with this :
private function buildQuilt($fund_type)
{
$path = storage_path() . "/data.json";
$json = json_decode(file_get_contents($path), true);
return array_map(function ($v) {
natsort($v);
return $v;
}, $json);
}
this will output:
Array (
[2007] => Array (
[number-sa] => -10
[number-ef] => 2
[number-xx] => 5
[number-ab] => 28
[number-aa] => 30
)
[2008] => Array (
[number-xx] => -1
[number-aa] => 0.5
[number-ef] => 23
[number-ab] => 43
[number-sa] => 55
)
)
live demo : https://3v4l.org/NHh7p
and if you want to reverse the order of your years keys , https://3v4l.org/YX3Ju
I want sort to each node under the "year" descending order and return it back in a function
to sort your 2-D array descending, you may use rsort
instead :
private function buildQuilt($fund_type)
{
$path = storage_path() . "/data.json";
$json = json_decode(file_get_contents($path), true);
return array_map(function ($v) {
rsort($v);
return $v;
}, $json);
}
this will output :
Array
(
[2007] => Array
(
[0] => 30
[1] => 28
[2] => 5
[3] => 2
[4] => -10
)
[2008] => Array
(
[0] => 55
[1] => 43
[2] => 23
[3] => 0.5
[4] => -1
)
)
Upvotes: 1
Reputation: 15141
Are you expecting this?
<?php
ini_set("display_errors", 1);
$json='{
"2007":{
"number-xx" : "5",
"number-aa" : "30",
"number-ef" : "2",
"number-sa" : "-10",
"number-ab" : "28"
},
"2008":{
"number-xx" : "-1",
"number-aa" : "0.5",
"number-ef" : "23",
"number-sa" : "55",
"number-ab" : "43"
}
}';
$data=json_decode($json,true);
$result=array();
foreach($data as $key=>$nodeData)
{
asort($nodeData);
$result[$key]= $nodeData;
}
print_r($result);
Output:
Array
(
[2007] => Array
(
[number-sa] => -10
[number-ef] => 2
[number-xx] => 5
[number-ab] => 28
[number-aa] => 30
)
[2008] => Array
(
[number-xx] => -1
[number-aa] => 0.5
[number-ef] => 23
[number-ab] => 43
[number-sa] => 55
)
)
Upvotes: 1