0

With an array like this, how would you sort the content array on the time inside the JSON value?

Array
(
    [id] => 18
    [content] => Array
        (
            [0] => Array
                (
                    [id] => 39795
                    [json] => {"last_modified": "2016-05-07 13:40:28", "time": "53"}
                )
            [1] => Array
                (
                    [id] => 39795
                    [json] => {"last_modified": "2016-05-07 14:18:06", "time": "90"}
                )
        )
)
Vince Lowe
  • 3,521
  • 7
  • 36
  • 63
  • 1
    Sort the array and while doing it decode the json to access the time value ([How to sort](http://stackoverflow.com/q/17364127); [Get that data out of dat json thing](http://stackoverflow.com/q/29308898)). Of course compare the timestamps of your time values for the sorting. – Rizier123 Jun 24 '16 at 15:11
  • If this is what the actual data looks like (ISO 8601 date strings), you don't even have to decode the json. Sorting alphabetically will sort the dates in ascending/descending order anyway, because the ISO date format basically is YmdHis... – Elias Van Ootegem Jun 24 '16 at 15:16
  • @EliasVanOotegem That would lead to some nasty bugs just when they change the time format or change the order of the values before encoding it to json :) – Rizier123 Jun 24 '16 at 15:18
  • @Rizier123: yeah, I wouldn't recommend it, but in this case, I'd say there's an X-Y problem at play: if you have an array with json encoded data, you probably should fix the data representation first. By the time you have an array like this, the JSON should be decoded already IMO. Nevertheless, you're right: ***sorting by string is not to be recommended in this case*** should've stressed that in my initial comment – Elias Van Ootegem Jun 24 '16 at 15:23

1 Answers1

0

Thanks, this works

usort( $response['content'], function ($a, $b) {
    $aJson = json_decode( $a['json'], true );
    $bJson = json_decode( $b['json'], true );

    return $aJson['time'] > $bJson['time'] ? -1 : 1;
} );
Vince Lowe
  • 3,521
  • 7
  • 36
  • 63