假设我有一个PHP 2-d数组,格式如下:
$json = [
{"value": "New", "date": $date},
{"value": "Open", "date": $date},
{"value": "Close", "date": $date}
]
$array = json_decode($json);
如果日期是m / d / Y格式的日期时间,我如何按最早到最晚的日期对数组元素进行排序?
答案 0 :(得分:1)
给出如下数据:
$json = '[ {"value": "New", "date": "06/21/2013"}, {"value": "Open", "date": "06/20/2013"}, {"value": "Close", "date": "06/22/2013"} ]';
$array = json_decode($json, TRUE);//array of objects, so set second parameter to TRUE
usort($array, function ($a, $b){
return strtotime($a['date']) - strtotime($b['date']);
});
print_r($array);
返回一个数组数组。如果要将其保留为对象数组并将其重新编码为JSON,则可以使用以下命令:
$array = json_decode($json);
$ord = array_map(function($a) {return $a->date;}, $array);
array_multisort($ord, $array);
$json = json_encode($array);