如何反转数组

时间:2014-05-15 21:49:45

标签: php arrays sorting

所以这是我的数组,我尝试了rsortarray_reverse但是它按数字排序并且不是我想要的。我只是想以相反的顺序。

[15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16]

4 个答案:

答案 0 :(得分:0)

您需要将true添加到array_reverse

array array_reverse ( array $array [, bool $preserve_keys = false ] )

换句话说,尝试这样的事情:

array_reverse( $yourArray, true);

这样您的密钥就会被保留,并且您可以获得所需的密钥。

答案 1 :(得分:0)

array_reverse应该可以工作。我刚做了这个测试:

$array = array(15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16);
$rArray = array_reverse($array);

print_r($array);
print_r($rArray);

结果是:

//for $array
Array ( [0] => 15 [1] => 14 [2] => 13 [3] => 12 [4] => 11 [5] => 10 [6] => 9 [7] => 8 [8] => 7 [9] => 6 [10] => 5 [11] => 4 [12] => 3 [13] => 2 [14] => 1 [15] => 30 [16] => 29 [17] => 28 [18] => 27 [19] => 26 [20] => 25 [21] => 24 [22] => 23 [23] => 22 [24] => 21 [25] => 20 [26] => 19 [27] => 18 [28] => 17 [29] => 16 )

//for $rArray
Array ( [0] => 16 [1] => 17 [2] => 18 [3] => 19 [4] => 20 [5] => 21 [6] => 22 [7] => 23 [8] => 24 [9] => 25 [10] => 26 [11] => 27 [12] => 28 [13] => 29 [14] => 30 [15] => 1 [16] => 2 [17] => 3 [18] => 4 [19] => 5 [20] => 6 [21] => 7 [22] => 8 [23] => 9 [24] => 10 [25] => 11 [26] => 12 [27] => 13 [28] => 14 [29] => 15 ) 

答案 2 :(得分:0)

自己动手,更有趣的解决方案:

$oldArray = array(15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16);
$length = count($oldArray);
$start= $length - 1;
$newArray=array();
for ($x = $start; $x >=0; $x--)
{
  array_push($newArray,$oldArray[$x]);
}
print_r($newArray);

打印:

Array ( [0] => 16 [1] => 17 [2] => 18 [3] => 19 [4] => 20 [5] => 21 [6] => 22 [7] => 23 [8] => 24 [9] => 25 [10] => 26 [11] => 27 [12] => 28 [13] => 29 [14] => 30 [15] => 1 [16] => 2 [17] => 3 [18] => 4 [19] => 5 [20] => 6 [21] => 7 [22] => 8 [23] => 9 [24] => 10 [25] => 11 [26] => 12 [27] => 13 [28] => 14 [29] => 15 ) 

答案 3 :(得分:0)

为了反转数组,只需将其放入堆栈(或至少使用该逻辑)。

FILO(倒数第一)因此你换了订单。

围绕php堆栈的Stack Overflow问题可以在这里找到: PHP Stack Implementation

您熟悉其他语言吗?我没有太多使用PHP。

只需创建一个新对象并添加结束即可。防爆 新阵列a a.push(oldArray.removelast())...