Wednesday, 29 August 2018

Sort a multidimensional array defined by the user

I have a user defined multidimensional array that I am trying to sort. I looked around, and say only how to sort single dimensional arrays, or associative arrays with keys... So, if I have the following...

$treasure = array( array("Banana", "Yellow"),
    array("Apple", "red"),
    array("Pear", "green"),
    array("Peach", "orange"),
    array("Orange", "orange"),
    array("Kiwi", "green"));

How do I sort the array so the first element of the interior array is alphabetical? So I would end up with...
$treasure = array( array("Apple", "red"),
    array("Banana", "Yellow"),
    array("Kiwi", "green")
    array("Orange", "orange"),
    array("Peach", "orange"),
    array("Pear", "green"),
    );


You could use usort:
<?php
function cmp($a, $b)
{
    return strcmp(reset($a), reset($b));
}

usort($treasure , "cmp");

0 comments:

Post a Comment