標籤:temp reac pos each php 實現 foreach [1] --
php裡面有個函數可以反轉數組,工作中也經常用到,非常方便。今天來自己實現這樣的功能。
$arr = [2,5,6,1,8,16,12];function reverse($arr){ $left = 0; $right = count($arr) -1; $temp = []; while ($left <= $right){ $temp[$left] = $arr[$right]; $temp[$right] = $arr[$left]; $left++; $right--; } ksort($temp); return $temp;}效果Array( [0] => 12 [1] => 16 [2] => 8 [4] => 6 [5] => 5 [6] => 2)
不過這個函數只能處理一維數組。在實現一個可以處理多維的。
$arr = [2,[6,3,9],1,[5,2,1,[10,8,7]],5,0];function reverse_arr($arr){ $index = 0; $reverse_array = []; foreach ($arr as $sub_arr){ if(is_array($sub_arr)){ $sub_arr = reverse($sub_arr); $arr_ = reverse_arr($sub_arr); $reverse_array[$index] = $arr_; }else{ $reverse_array[$index] = $sub_arr; } $index++; } return $reverse_array;}print_r(reverse(reverse_arr($arr)));
輸出結果
Array( [0] => 0 [1] => 5 [2] => Array ( [0] => Array ( [0] => 7 [1] => 8 [2] => 10 ) [1] => 1 [2] => 2 [3] => 5 ) [3] => 1 [4] => Array ( [0] => 9 [1] => 3 [2] => 6 ) [5] => 2)
php實現數組反轉