0

I have a nested JSON array within PHP which contains the following fields:

{
  "items": [{
        "id": "8498",
        "title": "Item 2",
        "pubdate": "2015-03-01 10:29:00 +0000",
     }, {
       "id": "8497",
        "title": "Item 1",
        "pubdate": "2015-03-01 16:29:00 +0000",
    }
  }]
}

and I would like to re-order the nodes in the Items array so that they are ordered first by pubdate (oldest to newest), and then within pubdate, for each time, by ID (smallest to largest), if that makes sense?

Currently i'm using the below function, but it only accepts 1 sort value (which im currently using to pubdate). Could I modify it to accept two, in the manner above?

function subval_sort($a,$subkey) {
foreach($a as $k=>$v) {
    $b[$k] = strtolower($v[$subkey]);
}
asort($b);
foreach($b as $key=>$val) {
    $c[] = $a[$key];
}
return $c;
}



$json_o['items'] = subval_sort($json_o['items'],'pubdate');
John Bergqvist
  • 852
  • 13
  • 38

3 Answers3

0

Try using usort
Live on ide1: http://ideone.com/gJGEON

$arr = json_decode($json, true);
$items = $arr['items'];

usort($items, function($a, $b) {
    if ($a['pubdate'] == $b['pubdate'])
        return $a['id'] < $b['id'];

    return ($a['pubdate'] < $b['pubdate']) ? -1 : 1;
});
dynamic
  • 46,985
  • 55
  • 154
  • 231
0

By adapting the answer here written by @Rob you can create a more general solution.

function subval_sort($a, $key1, $asc1, $key2, $asc2) { 
    # get a list of sort columns and their data to pass to array_multisort
    $sort = array();
    foreach($a as $k=>$v) {
        $sort[$key1][$k] = $v[$key1];
        $sort[$key2][$k] = $v[$key2];
    }
    $sortDesc1 = $asc1 ? SORT_ASC : SORT_DESC;
    $sortDesc2 = $asc2 ? SORT_ASC : SORT_DESC;

    # sort by event_type desc and then title asc
    array_multisort($sort[$key1], $sortDesc1, $sort[$key2], $sortDesc2,$a);
}

You would invoke it like so:

$json_o['items'] = subval_sort($json_o['items'], 'pubdate', false, 'id', true); 
Community
  • 1
  • 1
rjensen
  • 28
  • 5
-1

Using the solution linked by @Gal solved it :)

$sort = array();
foreach($json_o['items'] as $k=>$v) {
$sort['pubdate'][$k] = $v['pubdate'];
$sort['id'][$k] = $v['id'];
}
array_multisort($sort['pubdate'], SORT_ASC, $sort['id'], SORT_ASC,$json_o['items']);
John Bergqvist
  • 852
  • 13
  • 38