重新安排php关联数组

abs*_*ntx 5 php arrays associative-array multidimensional-array

我有一个数组:

$example = array();

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

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

$example ['three'] = array('fifth' => 'orange',
                           'sixth' => 'white');
Run Code Online (Sandbox Code Playgroud)

根据函数的一些输入,我需要在foreach循环处理输出之前更改示例数组的顺序:

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;
}
Run Code Online (Sandbox Code Playgroud)

如果不重新设计我的所有代码,有没有一种简单的方法可以做到这一点?我有一个非常深入的foreach循环来完成处理,如果有一个简单的方法来简单地重新排序数组,每次真正有用.

Fab*_*ler 2

您可以用于array_multisort您的排列。我假设您知道排列并且不需要从键名称中导出它。假设您想要 order two, three, one,然后创建一个像这样的引用数组

$permutation = array(3, 1, 2);
Run Code Online (Sandbox Code Playgroud)

含义:第一项转到位置 3,第二项转到位置 1,第三项转到位置 2

然后,在switch, 之后进行排列:

array_multisort($permutation, $example);
Run Code Online (Sandbox Code Playgroud)

这将对$permutation数组进行排序并将相同的顺序应用于$example