Hi everyone

I have an array:

Array
(
    [Name 1] => Array
        (
            [0] => 200
            [1] => 150
            [2] => 0
        )

[Name 2] => Array
    (
        [0] => 0
        [1] => 300
        [2] => 0
    )

[Name 3] => Array
    (
        [0] => 1000
        [1] => 1000
        [2] => 1000
    )

)

I need to sort the array by the sum of the subarray values; in the above case the new order would be:

Array
(
    [Name 3] => Array
        (
            [0] => 1000
            [1] => 1000
            [2] => 1000
        )

[Name 1] => Array
    (
        [0] => 200
        [1] => 150
        [2] => 0
    )

[Name 2] => Array
    (
        [0] => 0
        [1] => 300
        [2] => 0
    )

)

I've tried looking at usort but I can't work out how to use array_sum with it.

Can anyone help please?

Thank you

    Halfway there !

    // $resultarray is the input array
    
    function sort_function(array $a, array $b) {
        $arr1_val = array_sum($a);
        $arr2_val = array_sum($b);
        return $arr2_val - $arr1_val;
    }
    
    usort($resultarray,sort_function);
    
    print_r ($resultarray);
    
    

    Array is now sorted with the largest sums at the top, but the keys have gone!

    Anyone know what might be incorrect here?

    Thanks again.

      And... fixed by replacing usort with uasort.

      I didn't know about uasort - I didn't even know about usort until today so a different version that maintains keys wasn't expected.

      Any comments welcome though.

        Write a Reply...