Sort php associative 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 function input, I need to reorder the array example 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 reorganizing all my code? I have a pretty simple foreach loop that does the processing, and if there was an easy way to simply reorder the array every time, that would be really useful.

+5
source share
4 answers

array_multisort . , . , two, three, one, :

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

: 3, 1, 2

switch, permute:

array_multisort($permutation, $example);

$permutation $example.

+2

. , uksort().

uksort($example, function ($a, $b) use $type {
    switch($type) {
        case 'a':
            if ($a === 'one' || $b === 'three') return 1;
            if ($a === 'three' || $b === 'one') return -1;
            if ($a === 'two' && $b === 'three') return 1;
            return -1;
            break;
        // and so on...
    }
});
+2

, usort. . .

0

, , , .

0
source

All Articles