Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

re arrange 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 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.

like image 685
absentx Avatar asked Oct 05 '22 21:10

absentx


2 Answers

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.

like image 138
Fabian Schmengler Avatar answered Oct 10 '22 02:10

Fabian Schmengler


You are not going to find a silver bullet answer here. You are going to probably need to write your own function for use with 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...
    }
});
like image 21
Mike Brant Avatar answered Oct 10 '22 03:10

Mike Brant