ThaFlaxx ThaFlaxx - 6 months ago 14
PHP Question

Sort Multi-dimensional Array by Value from API

I already took a look at this Question and Solution, but this did not help me.

I am using

$champ_data = file_get_contents();


to get the Data from an API.
The API response the following

{
"data": {
"Aatrox": {
"id": 266,
"title": "the Darkin Blade",
"name": "Aatrox",
"key": "Aatrox"
},
"Thresh": {
"id": 412,
"title": "the Chain Warden",
"name": "Thresh",
"key": "Thresh"
}
}
} //this is not all of the data, it contains more than 100 ids


Because I cannot use $champ_data in any way yet, I decode it with

$champ_data = json_decode($champ_data);


Afterwards convert it into an Array (at least i hope so :P)

$data = 'data';
$champ_data = print_r(get_object_vars($champ_data->$data));


Now I was trying to sort it with the solutions from the other thread, so i did:

usort($champ_data, function($a, $b) {
return $a['id'] - $b['id'];
});


But it is not even sorting... It doesnt matter ASC or DESC.

Am I doing something wrong with the conversions? Where are my mistakes?

I just started programming like a week ago.

Thanks for all answers. :)

Answer

Just change $champ_data to $champ_data['data'] and add true to json_decode to decode to array otherwise you will get object array.

<?php

$champ_data = '{
   "data": {
      "Aatrox": {
         "id": 266,
         "title": "the Darkin Blade",
         "name": "Aatrox",
         "key": "Aatrox"
      },
      "Thresh": {
         "id": 412,
         "title": "the Chain Warden",
         "name": "Thresh",
         "key": "Thresh"
      }
   }
}';

$champ_data = json_decode($champ_data, true);

echo "<pre>";

print_r($champ_data['data']);

usort($champ_data['data'], function($a, $b) {
    return $a['id'] - $b['id'];
});

print_r($champ_data);

For descending sorting, just use

return $b['id'] - $a['id'];

Demo