我想按两个字段对数组进行排序。我的意思是说我有一个类似的数组: -
Array
(
[0] => Array
(
[name] => abc
[url] => http://127.0.0.1/abc/img1.png
[count] => 69
[img] => accessoire-sets_1.jpg
)
[1] => Array
(
[name] => abc2
[url] => http://127.0.0.1/abc/img12.png
[count] => 73
[img] =>
)
[2] => Array
(
[name] => abc45
[url] => http://127.0.0.1/abc/img122.png
[count] => 15
[img] => tomahawk-kopen_1.png
)
[3] => Array
(
[name] => zyz
[url] => http://127.0.0.1/abc/img22.png
[count] => 168
[img] =>
)
[4] => Array
(
[name] => lmn
[url] => http://127.0.0.1/abc/img1222.png
[count] => 10
[img] =>
)
[5] => Array
(
[name] => qqq
[url] => http://127.0.0.1/abc/img1222.png
[count] => 70
[img] =>
)
[6] => Array
(
[name] => dsa
[url] => http://127.0.0.1/abc/img1112.png
[count] => 43
[img] =>
)
[7] => Array
(
[name] => wer
[url] => http://127.0.0.1/abc/img172.png
[count] => 228
[img] =>
)
[8] => Array
(
[name] => hhh
[url] => http://127.0.0.1/abc/img126.png
[count] => 36
[img] =>
)
[9] => Array
(
[name] => rrrt
[url] => http://127.0.0.1/abc/img12.png
[count] => 51
[img] =>
)
[10] => Array
(
[name] => yyy
[url] => http://127.0.0.1/abc/img12.png
[count] => 22
[img] =>
)
[11] => Array
(
[name] => cxz
[url] => http://127.0.0.1/abc/img12.png
[count] => 41
[img] =>
)
[12] => Array
(
[name] => tre
[url] => http://127.0.0.1/abc/img12.png
[count] => 32
[img] =>
)
[13] => Array
(
[name] => fds
[url] => http://127.0.0.1/abc/img12.png
[count] => 10
[img] =>
)
)
数组没有图像(字段“img”)应始终放在数组WITH图像下面。在此之后,将对数组中的产品数量(字段数)进行排序。
意味着我必须首先根据img然后计数来显示排序数组。
我正在使用
usort( $childLinkCats, 'sortempty' );`
function sortempty( $a, $b ) {
return empty( $a['img'] );
}
它将显示图像值高于包含空值的数组。
并使用
对计数进行排序usort($childLinkCats, "_sortByCount");
function _sortByCount($a, $b) {
return strnatcmp($a['count'], $b['count']);
}
它将按计数缩短
但我面临的问题是,一次只能工作一次,但我必须同时使用这两种,请帮助我。
答案 0 :(得分:1)
编写一个调用两个比较函数的函数:
usort($childLinkCats, function($a, $b) {
if (empty($a['img']) == empty($b['img'])) {
return _sortByCount($a, $b);
} else {
return sortempty($a, $b);
}
});
您需要确保_sortByCount
和sortempty
返回正确的值。比较函数必须返回-1,0或1,而不是true或false。