我有一个json数组,如下所示,我想按大小对它进行排序
Array
(
[0] => {"file_name":"Desert - Copy.jpg","content_type":"image'/jpeg","tmp_path":"'/var'/www'/mywebsite.com'/public_html'/www'/tmp'/0000000012","sha256":"010f60d2927a35d0235490136ef9f4953b7ee453073794bcaf153d20a64544ea","size":"845941"}
[1] => {"file_name":"Hydrangeas - Copy.jpg","content_type":"image'/jpeg","tmp_path":"'/var'/www'/mywebsite.com'/public_html'/www'/tmp'/0000000013","sha256":"3b92fede080f9b0ec902afc58831191b5b8ccbaf6732352fd7a8b445d1e9f0bd","size":"595284"}
[2] => {"file_name":"Tulips.jpg","content_type":"image'/jpeg","tmp_path":"'/var'/www'/mywebsite.com'/public_html'/www'/tmp'/0000000014","sha256":"b9352f2565260219db72fc1fc896113a26c85866b69c50d3970c4d9f5cce830a","size":"620888"}
)
结果预期:
Array
(
[0] => {"file_name":"Hydrangeas - Copy.jpg","content_type":"image'/jpeg","tmp_path":"'/var'/www'/mywebsite.com'/public_html'/www'/tmp'/0000000013","sha256":"3b92fede080f9b0ec902afc58831191b5b8ccbaf6732352fd7a8b445d1e9f0bd","size":"595284"}
[1] => {"file_name":"Tulips.jpg","content_type":"image'/jpeg","tmp_path":"'/var'/www'/mywebsite.com'/public_html'/www'/tmp'/0000000014","sha256":"b9352f2565260219db72fc1fc896113a26c85866b69c50d3970c4d9f5cce830a","size":"620888"}
[2] => {"file_name":"Desert - Copy.jpg","content_type":"image'/jpeg","tmp_path":"'/var'/www'/mywebsite.com'/public_html'/www'/tmp'/0000000012","sha256":"010f60d2927a35d0235490136ef9f4953b7ee453073794bcaf153d20a64544ea","size":"845941"}
)
如何高效地完成这个任务
<?php
function sortByYear($a, $b) {
$dA = new DateTime($a['date']);
$dB = new DateTime($b['date']);
return $dA->format('y') - $dB->format('y');
}
$data = '{"info":[{"id":1, "title":"original title", "name":"john doe", "date":"2010-05-15"}, {"id":2, "title":"another title", "name":"foo bar", "date":"2009-04-11"}]}';
$d = json_decode($data, true);
$info = $d['info'];
usort($info, 'sortByYear');
print_r($info);
?>
来源: http://codepad.org/6N4fmbKG
如何用PHP对JSON数组进行排序这是我想到的,但我欢迎更有效的解决方案
function sort_json($json_array)
{
if (count($json_array) > 1) {
//convert to array
foreach ($json_array as &$json) {
$array[] = json_decode($json);
}
// sort in ascending order by size
usort($array, function($a, $b)
{
return $a->size < $b->size ? -1 : 1; //Compare the sizes
});
//convert back to json
$json_array = array();
foreach ($array as &$a) {
$json_array[] = json_encode($a);
}
}
return $json_array;
}
使用以下代码:
function sortBySize($a, $b)
{
if ($a['size'] == $b['size']) return 0;
return ($a['size'] < $b['size']) ? -1 : 1;
}
usort($data, "sortBySize");
如何使用工作k: http://www.w3schools.com/php/func_array_usort.asp