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.
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
.
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...
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With