©
Dieses Dokument verwendet PHP-Handbuch für chinesische Websites Freigeben
(PHP 4, PHP 5, PHP 7)
array_reverse — 返回一个单元顺序相反的数组
$array
[, bool $preserve_keys
= false
] ) array_reverse() 接受数组
array
作为输入并返回一个单元为相反顺序的新数组。
array
输入的数组。
preserve_keys
如果设置为 TRUE
会保留数字的键。
非数字的键则不受这个设置的影响,总是会被保留。
返回反转后的数组。
版本 | 说明 |
---|---|
4.0.3 |
添加了参数 preserve_keys 。
|
Example #1 array_reverse() 例子
<?php
$input = array( "php" , 4.0 , array( "green" , "red" ));
$result = array_reverse ( $input );
$result_keyed = array_reverse ( $input , true );
?>
这将使 $result 和 $result_keyed 具有相同的单元,但是注意键名的区别。 $result 和 $result_keyed 的打印输出显示分别为:
Array ( [0] => Array ( [0] => green [1] => red ) [1] => 4 [2] => php ) Array ( [2] => Array ( [0] => green [1] => red ) [1] => 4 [0] => php )
[#1] atulmvAThotmailDOTcoDOTuk [2012-08-29 11:48:15]
Here are a couple of routines to swap the order of two elements in an array
<?php
function array_swap_forward($arr,$elem)
{
$ndx = array_search($elem,$arr) - 1;
$b4 = array_slice($arr,0,$ndx);
$mid = array_reverse(array_slice($arr,$ndx,2));
$after = array_slice($arr,$ndx + 2);
return array_merge($b4,$mid,$after);
}
function array_swap_back($arr,$elem)
{
$ndx = array_search($elem,$arr);
$b4 = array_slice($arr,0,$ndx);
$mid = array_reverse(array_slice($arr,$ndx,2));
$after = array_slice($arr,$ndx + 2);
return array_merge($b4,$mid,$after);
}
$arr =array('a','b','c','d','e','f');
print_r(array_swap_forward($arr,'c'));
echo '<br>';
print_r(array_swap_back($arr,'c'));
?>
[#2] alfbennett at gmail dot com [2010-04-06 13:41:43]
Needed to just reverse keys. Don't flog me if there is a better way. This was a simple solution.
<?php
function array_reverse_keys($ar){
return array_reverse(array_reverse($ar,true),false);
}
?>
[#3] rahulavhad at yahoo dot com [2000-12-29 20:31:09]
This code can help in recursive reversing of the array...
<?php
$arr1 = array(2,1,array(5,2,1,array(9,8,7)),5,0);
$arr1 = array_reverse($arr1);
function Reverse_Array($array)
{ $index = 0;
foreach ($array as $subarray)
{ if (is_array($subarray))
{ $subarray = array_reverse($subarray);
$arr = Reverse_Array($subarray);
$array[$index] = $arr;
}
else {$array[$index] = $subarray;}
$index++;
}
return $array;
}
$arr2 = Reverse_Array($arr1);
?>