Search code examples
phparrayssortingmultidimensional-array

Sort a multidimensional array by a column


My array $servers looks like this

Array
(
    [0] => Array
        (
            [0] => Dell PowerEdge R210 II
            [1] => 8
            [2] => Array()
        )

    [1] => Array
        (
            [0] => Dell PowerEdge R210 II 2
            [1] => 2
            [2] => Array()
        )

    [2] => Array
        (
            [0] => Dell PowerEdge R210 II 3
            [1] => 3
            [2] => Array()
        )

    [3] => Array
        (
            [0] => Dell PowerEdge R210 II 4
            [1] => 4
            [2] => Array()
        )

    [4] => Array
        (
            [0] => Dell PowerEdge R210 II 5
            [1] => 5
            [2] => Array()
        )

    [5] => Array
        (
            [0] => Dell PowerEdge R210 II 6
            [1] => 6
            [2] => Array()
        )
)

I'd like to have the array re-arranged and put back into $servers but in order of $servers[x][1]

So where the singular number is (1st object is 8) I'd like it to sort it with the smallest number 1st, moving to the largest!

ps I tried this

<?php
function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

usort($servers, "cmp");
?>

but it didnt seem to work!


Solution

  • Your cmp is wrong. $a and $b are arrays like

    Array
        (
            [0] => Dell PowerEdge R210 II 6
            [1] => 6
            [2] => Array
                (
                    [0] => 6
                    [1] => Sock
                    [2] => Price
                    [3] => ImageURL
                    [4] => CPU
                    [5] => Memory
                    [6] => HDD
                    [7] => Bandwidth
                    [8] => OS
                    [9] => Upgrades
                    [10] => OrderLink
                )
    
        )
    

    and you must compare $a[1] with $b[1]:

    function cmp($a, $b) {
        return $a[1] - $b[1];
    }