排序数组时遇到问题。
我有一个像我这样的类别的数组:
Array
(
[0] => Array
(
[title] => category
[url] => http//mycategoryurl
[subcategory] => Array
(
[0] => Array
(
[title] => category - first
[url] => http//mycategoryurl
)
[1] => Array
(
[title] => category - first
[url] => http//mycategoryurl
)
[2] => Array
(
[title] => category - first
[url] => http//mycategoryurl
)
)
)
[1] => Array
(
[title] => category
[url] => http//mycategoryurl
[subcategory] => Array
(
[0] => Array
(
[title] => category - first
[url] => http//mycategoryurl
)
[1] => Array
(
[title] => category - first
[url] => http//mycategoryurl
)
[2] => Array
(
[title] => category - first
[url] => http//mycategoryurl
)
[3] => Array
(
[title] => category - first
[url] => http//mycategoryurl
)
)
)
[2] => Array
(
[title] => category
[url] => http//mycategoryurl
[subcategory] => Array
(
[0] => Array
(
[title] => category - first
[url] => http//mycategoryurl
)
[1] => Array
(
[title] => category - first
[url] => http//mycategoryurl
)
)
)
)
我希望count(subcategory)
像这样对这个数组进行排序:
Array
(
[0] => Array
(
[title] => category
[url] => http//mycategoryurl
[subcategory] => Array
(
[0] => Array
(
[title] => category - first
[url] => http//mycategoryurl
)
[1] => Array
(
[title] => category - first
[url] => http//mycategoryurl
)
[2] => Array
(
[title] => category - first
[url] => http//mycategoryurl
)
[3] => Array
(
[title] => category - first
[url] => http//mycategoryurl
)
)
)
[1] => Array
(
[title] => category
[url] => http//mycategoryurl
[subcategory] => Array
(
[0] => Array
(
[title] => category - first
[url] => http//mycategoryurl
)
[1] => Array
(
[title] => category - first
[url] => http//mycategoryurl
)
[2] => Array
(
[title] => category - first
[url] => http//mycategoryurl
)
)
)
[2] => Array
(
[title] => category
[url] => http//mycategoryurl
[subcategory] => Array
(
[0] => Array
(
[title] => category - first
[url] => http//mycategoryurl
)
[1] => Array
(
[title] => category - first
[url] => http//mycategoryurl
)
)
)
)
请帮我按照我的例子对这个数组进行排序。
答案 0 :(得分:3)
您想要使用usort功能,如下所示:
usort($arrayToSort, function($a, $b){
$aCount = count($a['subcategory']);
$bCount = count($b['subcategory']);
if ($aCount == $bCount) {
return 0;
}
//flip the '>' to '<' for ascending sort. It is set to do descending
return ($aCount > $bCount) ? -1 : 1;
});
答案 1 :(得分:2)
使用usort
函数进行回调:
$arr = array(); // your array
usort($arr, function($a, $b) { return count($a['subcategory']) < $count($b['subcategory'])? -1 : 1; });
print_r($arr);