Php sort multidimensional array by value alphabetically

Here is your answer and it works 100%, I've tested it.

 [PHP >= 5.5] and  it becomes possible to build your sortings [sorting by one or many fields]:

scott - evolove - net - work it out

16 years ago

A very simple way to sort an array of associative arrays by some value is to use usort.

I needed to sort an array of 20 data structures by their 'distance' value:

Array
[
    [0] => Array
        [
            [blahblah] => blahblah
            [distance] => 6
        ]

    [1] => Array
        [
          you get the idea....

Here's the code:

--------------------
usort[$results, "distributor_compare"];

/**
* usort callback
*/
function distributor_compare[$a, $b] {
    $adist = intval[$a['distance']];
    $bdist = intval[$b['distance']];

        if [$adist == $bdist] {
     return 0;
     }
     return [$adist < $bdist] ? -1 : 1;   
}
--------------------

mech.cx

13 years ago

I was [as near everyone here :-] looking to sort 2-dimensional arrays by certain fields in the associative sub-arrays.
What I didn't like about the documentation examples is that you need to loop through the input array to create sub arrays first, then use those in the function call.

"php a-t-the-r-a-t-e chir.ag" [//www.php.net/manual/en/function.array-multisort.php#60401] wrote a quite cunning wrapper function, I rewrote it slightly, changing variable names and adding comments [for my sanity :-] mostly.
One snag I found: the input array is passed to array_multisort as last argument, but the changed array is not the one that is returned. Passing it by reference fixed that. This seems to be caused by the whole thing sitting inside the call_user_func_array, as shown below.

Chủ Đề