I have this kind of array
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
I need to sort items in array by CLASS, but only when CLASS is equal "1", these items sort by PRICE, ASC and then sort the rest of array items only by PRICE (I don't care CLASS in this case anymore).
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)
I found and edit this function, which works fine with multiarrays and multi-sorting, but I can not figure out how to sort only part of array by CLASS I wrote above.
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);