Search code examples
phparrayssortingmultidimensional-array

Sort a 2d array by a column and preserve first level keys


I have the following array:

Array
(
[Address Line 1] => Array
    (
        [llx] => 18.96
        [lly] => 28.88999999999999
    )

[Address Line 2] => Array
    (
        [llx] => 18.73
        [lly] => 35.66
    )

[City State ZIP Code] => Array
    (
        [llx] => 18.51
        [lly] => 47.16999999999999
    )

[Full Name] => Array
    (
        [llx] => 18.86
        [lly] => 20.15999999999997
    )

 )

and I would like to loop through it and sort it by the lly value: so the final outcome should really be

Array
 (
[Full Name] => Array
    (
        [llx] => 18.86
        [lly] => 20.15999999999997
    )
    
[Address Line 1] => Array
    (
        [llx] => 18.96
        [lly] => 28.88999999999999
    )

[Address Line 2] => Array
    (
        [llx] => 18.73
        [lly] => 35.66
    )

[City State ZIP Code] => Array
    (
        [llx] => 18.51
        [lly] => 47.16999999999999
    )

  )

I've been looking over the sorting functions in PHP, but they seem to be mainly focused on single dimension arrayS and nothing like this unless I'm missing something.


Solution

  • Rudie provided an answer, but it is provably incorrect. Here's a solution using array_multisort.

    $llx = array();
    $lly = array();
    foreach ($array as $key => $row) {
        $llx[$key] = $row['llx'];
        $lly[$key] = $row['lly'];
    };
    array_multisort($lly, SORT_ASC, $llx, $array);