如何根据不会出现在所有元素中的值对php数组进行排序?
I am having a php array as follows;
$array =Array(
[310] => Array
(
[vendorname] => Utsav the vendor
)
[309] => Array
(
[vendorname] => Ashish vendor
[suggest_order] => 1
)
[308] => Array
(
[vendorname] => praveen rathod vendor
)
[262] => Array
(
[vendorname] => Yash Vendor
[suggest_order] => 0
)
[264] => Array
(
[vendorname] => amol vendro
[suggest_order] => 2
));
And I want to sort it based on suggest_order key so lowest suggest_order key's value should come first and than higher value and in last their comes all remaining elements which don't even have suggest_order key like;
$array =Array(
[262] => Array
(
[vendorname] => Yash Vendor
[suggest_order] => 0
)
[309] => Array
(
[vendorname] => Ashish vendor
[suggest_order] => 1
)
[264] => Array
(
[vendorname] => amol vendro
[suggest_order] => 2
)
[310] => Array
(
[vendorname] => Utsav the vendor
)
[308] => Array
(
[vendorname] => praveen rathod vendor
));
I have tried PHP Sort Array By SubArray Value .
function cmp_by_optionNumber($a, $b) {
return $a["suggest_order"] - $b["suggest_order"];
}
print_r(usort($array, "cmp_by_optionNumber"));
And I have also tried 2nd option in above answer,
$new_array=usort($array, function ($a, $b) {
return $a['suggest_order'] - $b['suggest_order'];
});
print_r($new_array);
But I am getting "1" in response; Any help will be appreciated.
All sort methods take the array to sort as reference. So you don't have to care about the return value, as the sorting is done in place.
function cmp_by_optionNumber($a, $b) {
return $a["suggest_order"] - $b["suggest_order"];
}
usort($array, "cmp_by_optionNumber");
print_r($array);
If you need to do some special handling for suggest_order, you could use isset
inside the sort function.
usort($array, function($a, $b) {
if (isset($a["suggest_order"]) && isset($b["suggest_order"])) {
return $a["suggest_order"] - $b["suggest_order"];
}
if (isset($a["suggest_order"])) {
return -1;
}
if (isset($b["suggest_order"])) {
return 1;
}
return 0;
});
to compare elements which have 'suggest_order' property with those which doesn't have you can use function like:
function cmp_by_optionNumber($a, $b) {
$lval = $a["suggest_order"]??-1;
$rval = $b["suggest_order"]??-1;
return $lval > $rval ? 1 : $rval > $lval ? -1 : 0;
}
this will properly order items as you want - by suggest_order key
also you do not want to print result of sort function but original array passed to sort function to see if it's sorted