Search code examples
phparrayssortingmultidimensional-arraynumeric

Sorting a 2d array by numeric column value


I have an array with some values which is being declared on the fly:

// a for loop that finds elements from source
$array[] = array($fruit, $color, $shape, $price);

later i have another for loop which displays the items in the array:

for($j = 0; $j < sizeof($array); $j++) {
    echo $array[$j][0]." ".$array[$j][1]." ".$array[$j][2]." ".$array[$j][3]."
             ".$array[$j][4];
}

I am able to display all the information i want properly, however i want to sort the array before displaying based on the $price. e.g

Orange orange round £.6
Mango yellow oval £.9
Apple red round £.4

I want it in the following form

Apple red round £.4
Orange orange round £.6
Mango yellow oval £.9

Using uasort: Before :

Array ( [0] => Array ( [0] => Orange [1] => red [2] => round [3] => .6) 
        [1] => Array ( [0] => Mango [1] => yellow [2] => oval [3] => .9)
        [2] => Array ( [0] => Apple [1] => red [2] => round [3] => .4));

function provided:

function my_cmp_func($a, $b) {
   if($a[3] == $b[3]){
       return -1*strcmp($a[4], $b[4]); // another column added for comparison
   }
   return -1*strcmp($a[3], $b[3]);     
}

uasort($array, 'my_cmp_func');
print_r($array);

Solution

  • you can do that using a custom comparing function

    so you start by using the usort function (if you don't need to keep the indexes) so you will call it like this:

    usort($array, 'my_cmp_func');
    

    and define the comparing function as:

    function my_cmp_func($a, $b)
    {
        return strcmp($a[3], $b[3]);    
    }
    

    I defined the function using the strcmp because I don't know if the pound sign is part of the value or you just added it now.. but you can define the function the way you want

    Edit: I added the sample here http://codepad.org/DxgFznzE to show that it works; and if you want to reverse the sort order just use this in the function:

    return -1*strcmp($a[3], $b[3]);
    

    instead of just the value you get from strcmp