0

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. :)

Community
  • 1
  • 1
ThaFlaxx
  • 71
  • 7
  • Want to sort by ascending or descending? – Thamilhan May 24 '16 at 00:55
  • You're way over complicating the sorting process here. Can you just read over your question again, saying it out loud, then ask yourself "what am I actually asking here?" then add that. It's looks like a simple problem and you've tried something already which is good, but it's also a simple solution - just need to know what it is – scrowler May 24 '16 at 00:56
  • Thanks for the answers. It doesnt matter ascending or descending, i would take both. I just dont know, where my mistakes are. I just started programming like a week ago. – ThaFlaxx May 24 '16 at 00:58

1 Answers1

4

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

Thamilhan
  • 13,040
  • 5
  • 37
  • 59
  • Wow, it looks like that "true" ind the json_decode helped.I should use ['data'] instead of ->$data, haha. Thanks a lot! – ThaFlaxx May 24 '16 at 01:15