如何在PHP中按多个值对JSON数组进行排序


How can I sort a JSON array by multiple values in PHP?

我在PHP中有一个嵌套的JSON数组,它包含以下字段:

{
  "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",
    }
  }]
}

我想重新排序Items数组中的节点,以便它们首先按pubdate(从最旧到最新)排序,然后在pubdate内,每次按ID(从最小到最大)排序,如果有意义的话?

目前我正在使用下面的函数,但它只接受1个排序值(我目前正在使用它来发布日期)。我可以按照上面的方式修改为接受两个吗?

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');

尝试使用usort
在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;
});

通过调整@Rob在这里编写的答案,您可以创建一个更通用的解决方案。

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);
}

你可以这样调用它:

$json_o['items'] = subval_sort($json_o['items'], 'pubdate', false, 'id', true); 

使用@Gal链接的解决方案解决了它:)

$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']);