$unresponsives = [
[
"Customer",
"172.52.46.75",
"2022-04-01 16:20:45",
"1817",
"nxlog",
"2327.02 Hours"
],
[
"Customer",
"172.25.89.45",
"2022-04-01 16:20:45",
"1817",
"nxlog",
"2327.02 Hours"
],
[
"Customer",
"172.19.10.94",
"2022-04-01 16:20:45",
"1817",
"nxlog",
"2327.02 Hours"
]]
This is an example from my array of arrays. I want to sort the arrays inside by their fifth element (hours) in descending order. I am able to achieve this with usort but in the array there are also arrays with the string "Undefined" as their fifth value. Example below:
[
"PreProd",
"178.18.15.12",
"\/",
"1502",
"iis",
"Undefined"
]
Currently they are listed at the bottom of the array after the sorting is done. I instead want them to be listed in the beginning of the array. So first arrays with undefined ones and then the rest in descending order. How can I achieve this?
Below is the usort function that I use:
usort($unresponsives, function ($unresponsive1, $unresponsive2) {
return floatval($unresponsive2[5]) <=> floatval($unresponsive1[5]);
});
array_multisortApproach - Example https://3v4l.org/SuJQXFor a slightly more complex approach that allows fine-grained control of the sorting as desired. Use
array_columnto retrieve the hours. Usearray_keyson the hours to determine the filtered value positions and iterate over the positions to assign them as a numeric value. Thenarray_multisortcan be used with the desired flags to sort the resulting arrays.Result
Ascending Numeric Sorting
To change the sort order to
SORT_ASCswap outPHP_INT_MAXforPHP_INT_MIN, depending on where in the array you want the filtered value to reside.Result
usortApproach - Example https://3v4l.org/Uoml6The same methodology of assigning the filtered value as a numeric value can be applied to
usortby manipulating the compared values of the desired filtered value(s) in a conditional, which will only be used to sort the array.Descending Order
Ascending Order
As with the
array_multisortapproach change the sort order by swappingPHP_INT_MAXwithPHP_INT_MINbut also swap the$b[5] <=> $a[5]comparison with$a[5] <=> $b[5]to sort the values in ascending order.