php 如何更改数组的顺序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2175350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change orders of array?
提问by user198729
$a = array(0=>'a',1=>'b',2=>'c', 3=>'d');
I want to change the order to be 3,2,0,1:
我想把顺序改成3,2,0,1:
$a = array(3=>'d',2=>'c',0=>'a', 1=>'b');
回答by Gordon
If you want to change the order programmatically, have a look at the various array sorting functions in PHP, especially
如果要以编程方式更改顺序,请查看PHP中的各种数组排序函数,尤其是
uasort()— Sort an array with a user-defined comparison function and maintain index associationuksort()— Sort an array by keys using a user-defined comparison functionusort()— Sort an array by values using a user-defined comparison function
uasort()— 使用用户定义的比较函数对数组进行排序并保持索引关联uksort()— 使用用户定义的比较函数按键对数组进行排序usort()— 使用用户定义的比较函数按值对数组进行排序
Based on Yannicks examplebelow, you could do it this way:
根据下面的Yannicks 示例,您可以这样做:
$a = array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd');
$b = array(3, 2, 0, 1); // rule indicating new key order
$c = array();
foreach($b as $index) {
$c[$index] = $a[$index];
}
print_r($c);
would give
会给
Array([3] => d [2] => c [0] => a [1] => b)
But like I said in the comments, if you do not tell us the rule by which to order the array or be more specific about your need, we cannot help you beyond this.
但就像我在评论中所说的那样,如果您不告诉我们订购阵列的规则或更具体地说明您的需求,除此之外我们无法为您提供帮助。
回答by Yannick Motton
Since arrays in PHP are actually ordered maps, I am unsure if the order of the items is preserved when enumerating.
由于 PHP 中的数组实际上是有序映射,因此我不确定在枚举时是否保留了项目的顺序。
If you simply want to enumerate them in a specific order:
如果您只想按特定顺序枚举它们:
$a = array(0=>'a',1=>'b',2=>'c', 3=>'d');
$order = array(3, 2, 0, 1);
foreach ($order as $index)
{
echo "$index => " . $a[$index] . "\n";
}
回答by Barmar
function reorder_array(&$array, $new_order) {
$inverted = array_flip($new_order);
uksort($array, function($a, $b) use ($inverted) {
return $inverted[$a] > $inverted[$b];
});
}
$a = array(0=>'a',1=>'b',2=>'c', 3=>'d');
reorder_array($a, array(3, 2, 0, 1));
var_dump($a);
Result:
结果:
Array ( [3] => d [2] => c [0] => a [1] => b )
回答by maciek
The easiest way to do it with uksort(), more functional way:
最简单的方法是使用uksort()更实用的方法:
$a = ['a','b','c','d'];
$order = [3, 2, 0, 1];
uksort($a, function($x, $y) use ($order) {
return array_search($x, $order) > array_search($y, $order);
});
print_r($a); // [3 → d, 2 → c, 0 → a, 1 → b]
回答by Sorin Ene
A more general aproach:
更通用的方法:
$ex_count = count($ex_names_rev_order);
$j = 0;
$ex_good_order = array();
for ($i=($ex_count - 1); $i >= 0 ; $i--) {
$ex_good_order[$j] = $ex_names_rev_order[$i];
$j++;
}
回答by Sarfraz
here is how
这是如何
krsort($a);

