phparrayssortingmultidimensional-arrayassociative-array

Sort an array according to another array


I have an array:

$example = array();

$example ['one']   = array('first' => 'blue',
                           'second' => 'red');

$example ['two']   = array('third' => 'purple',
                           'fourth' => 'green');

$example ['three'] = array('fifth' => 'orange',
                           'sixth' => 'white');

Based on some input to the function, I need to change the order of the example array before the foreach loop processes my output:

switch($type)

case 'a':
//arrange the example array as one, two three
break;

case 'b':
//arrange the example array as two, one, three
break;

case 'c':
//arrange the example array in some other arbitrary manner
break;

foreach($example as $value){
        echo $value;
}

Is there an easy way to do this without re-engineering all my code? I have a pretty indepth foreach loop that does the processing and if there was an easy way to simple re-order the array each time that would be really helpful.


Solution

  • You can use array_multisort for your permutation. I assume that you know the permutation and don't need to derive it from the key names. Say, you want the order two, three, one, then create a reference array like that:

    $permutation = array(3, 1, 2);
    

    Meaning: first item goes to position 3, second item to position 1, third item to position 2

    Then, after the switch, permute:

    array_multisort($permutation, $example);
    

    This will sort the $permutation array and apply the same order to $example.