1

I like to sort following JSON data by it's value salary using PHP in ascending order.

{
    "allresults": [
        {
            "results": [
                {
                    "Name": "Peter",
                    "salary": 1000
                }
            ]
        },
        {
            "results": [
                {
                    "Name": "Riya",
                    "salary": 999
                }
            ]
        }
    ]
}

Required Result:

  1. Riya : 999
  2. Peter : 1000
Alok
  • 17
  • 1
  • 6

3 Answers3

3

You can write a custom sort function using uasort. Something like this should work for you:

$data = json_decode($json, true);

uasort($data['allresults'], function($a, $b) {
    $aSalary = $a['results'][0]['salary'];
    $bSalary = $b['results'][0]['salary'];

    return $aSalary - $bSalary;
});

foreach($data['allresults'] as $item) {
    printf("%s: %d<br />", $item['results'][0]['Name'], $item['results'][0]['salary']);
}
alexn
  • 57,867
  • 14
  • 111
  • 145
0

play with this :

$jsonIterator = new RecursiveIteratorIterator(
        new RecursiveArrayIterator(your_json($file, TRUE)),
        RecursiveIteratorIterator::SELF_FIRST
    );

foreach ($jsonIterator as $key => $val) {
     //your control
}
WhiteLine
  • 1,919
  • 2
  • 25
  • 53
0

1st json to php array -> $json_arr = json_decode($json, true);

after that -> you can use array_multisort http://php.net//manual/en/function.array-multisort.php

rumaviio
  • 1
  • 1