[Solved] Sort Multi-Dimensional Array PHP


If I understand what you need to do, you can use usort:

usort($array, function($a, $b) {
    $sort = array('Red', 'Green', 'Blue');
    if (array_search($a['House_Colour'], $sort) > array_search($b['House_Colour'], $sort)) return 1;
    if (array_search($a['House_Colour'], $sort) < array_search($b['House_Colour'], $sort)) return -1;
    return 0;
});

If you can leverage on defines instead on relying on strings for the house colors the solutions will be straiforward and more efficient.

You should define the House colors in a static class (to simulate an enumerated type)

Class HouseColour {
    const Red = 0;
    const Green = 1;
    const Blue = 2;
}

In this case you have to declare an opponent/player

 $opponent = array ( 'Opponent'=>'Steve', 'House_Colour'=>HouseColour::Green);

If you are non confortable with class and static constants (you should be confortable with them as the benefits are really great) you can resort to a sequence of defines

define ('HC_Red',0);
define ('HC_Green', 1);
define ('HC_Blue', 2);

an opponent become

 $opponent = array ( 'Opponent'=>'Steve', 'House_Colour'=>HC_Green);

in both cases the usort function is the same:

usort($array, function($a, $b) {
    if ($a['House_Colour'] > $b['House_Colour']) return 1;
    if ($a['House_Colour'] < $b['House_Colour']) return -1;
    return 0;
});

solved Sort Multi-Dimensional Array PHP