Monday, April 3, 2017

Dynamically sorting specific JSON nodes and returning in PHP function

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.

Any help would be much appreciated!

Thank you.



via BaconJuice

Advertisement