我有这种数组
ID - CLASS - PRICE - NAME
1 - 1 - 400 - Product 1
2 - 3 - 120 - Product 2
3 - 1 - 350 - Product 3
4 - 2 - 600 - Product 4
5 - 2 - 320 - Product 5
我需要通过CLASS对数组中的项进行排序,但只有当CLASS相等时才会排序" 1",这些项按PRICE,ASC排序,然后仅按PRICE排序其余的数组项(我不&# 39;在这种情况下不再关心CLASS了。)
The result of sorting should be:
ID
3 (has CLASS == 1 and lower price then 1)
1 (has CLASS == 1 and higher price then 3)
2 (has CLASS != 1 (so rest of items sort only by price), lowest price)
5 (has CLASS != 1, middle price)
4 (has CLASS != 1, higher price)
我发现并编辑了这个函数,它适用于多个数组和多重排序,但我无法弄清楚如何通过上面写的CLASS来排序数组的一部分。
function sortMultiArray() {
$args = func_get_args();
$data = array_shift($args);
foreach($args as $n => $field) {
if (is_string($field)) {
$tmp = array();
foreach($data as $key => $row) {
$tmp[$key] = str_replace("-1", "999999999", $row[$field]);
}
$args[$n] = $tmp;
}
}
$args[] = &$data;
call_user_func_array('array_multisort', $args);
return array_pop($args);
}
// usage - sorting by price DESC, name ASC
$sortedArray = sortMultiArray($array, "price", SORT_DESC, 'name', SORT_ASC);