在php中的Reindex数组

时间:2017-03-13 08:21:08

标签: php arrays

我有这样的数组:

Array ( 
  [0] => Array ( [0] => Red [1] => Blue [2] => Black [3] => White [4] => Silver)
  [1] => Array ( [0] => Yellow [1] => Green [2] => Pink [3] => Purple)
  [2] => Array ( [0] => Orange [1] => Olive [2] => Lime)
etc..
)

预期数组:

Array ( 
   [0] => Red
   [1] => Blue
   [2] => Black
   [3] => White
   [4] => Silver
   [5] => Yellow  
   [6] => Green
   [7] => Pink
   [8] => Purple
   [9] => Orange
   [10] => Olive
   [11] => Lime
   etc..
) 

如何重构?我无法理解

谢谢!

4 个答案:

答案 0 :(得分:2)

您可以像这样使用array_merge功能......

<?php
$array1 = Array ( 
  [0] => Array ( [0] => Red [1] => Blue [2] => Black [3] => White [4] => Silver)
  [1] => Array ( [0] => Yellow [1] => Green [2] => Pink [3] => Purple)
  [2] => Array ( [0] => Orange [1] => Olive [2] => Lime)
etc..
)

$array2 = Array();
for($i=0; $i<$array1.length; $i++) {
    $array2 = array_merge($array2, $array1[$i]);
}

print_r($array2);
?>

答案 1 :(得分:1)

在php中有一种非常方便的内置方式。 Array_merg是一个将无限数量的参数组合成最终数组的函数。并且call_user_func_array会自动将参数填充到Array_merg中,因此我们可以通过单行完成目标:

<强> PHP

<?php

$workwith = Array ( 
    Array("Red", "Blue", "Black", "White", "Silver"),
    Array("Yellow", "Green", "Pink", "Purple"),
    Array("Orange", "Olive", "Lime")
);

$result = call_user_func_array("array_merge", $workwith);
print_r($result);

?>

<强>输出

    Array
(
    [0] => Red
    [1] => Blue
    [2] => Black
    [3] => White
    [4] => Silver
    [5] => Yellow
    [6] => Green
    [7] => Pink
    [8] => Purple
    [9] => Orange
    [10] => Olive
    [11] => Lime
)

答案 2 :(得分:0)

试试这个

f:format.crop

答案 3 :(得分:0)

使用array_walk_recursive

array_walk_recursive($ar, function($v, $k) use (&$list) {return $list[] = $v;});
print_r($list);

直播示例:https://3v4l.org/DRMKI