-1

Here is my JSON file:

    {
"example": "1",
"example2": 2,
"text": "3",
"info": {
    "agent": 4,
    "sum": 5,
    "collection": [{
        "Name": "6",
        "Pic": "7"
    }, {
        "Name": "8",
        "Pic": "9"
    }, {
        "Name": "10",
        "Pic": "11"
    }]
     }

      }

I display the results of the JSON file in a foreach loop:

$data = json_decode(file_get_contents('http://linktojson.com'));
foreach($data->info->collection as $key){

    echo $key->Pic;
    echo $key->Name;

  }

As you can see, 'Pic' has different numbers. How would I use sort() to make the largest number display at the top of the foreach loop and the lowest display at the bottom?

bob jomes
  • 261
  • 1
  • 4
  • 13

1 Answers1

-1

You need to use array_multisort here. Check Online

$json = '{
"example": "1",
"example2": 2,
"text": "3",
"info": {
    "agent": 4,
    "sum": 5,
    "collection": [{
        "Name": "6",
        "Pic": "7"
        }, {
            "Name": "8",
            "Pic": "9"
        }, {
            "Name": "10",
            "Pic": "11"
        }]
     }
}';

$result = json_decode ($json, true);
foreach($result  as $key => $value){
    if($key == 'info'){
        $keys = array_keys($value['collection']);
        array_multisort(
            array_column($value['collection'], 'Pic'), SORT_DESC, SORT_NUMERIC, $value['collection'], $keys
        );
        $value = array_combine($keys, $value['collection']);
        foreach($value as $val){
            echo $val['Pic']." - ".$val['Name']."<br/>";
        }
    }   
}

Result:

11 - 10
9 - 8
7 - 6
Murad Hasan
  • 9,233
  • 2
  • 16
  • 39