PHP通过步行合并2个阵列?

时间:2012-10-04 21:25:49

标签: php arrays

我有一个像这样的数组:

array(2) {
  [0]=>
  array(4) {
    [0]=>
    string(6) "04ba2c"
    [1]=>
    string(6) "f4a204"
    [2]=>
    string(6) "d40604"
    [3]=>
    string(6) "990000"
  }
  [1]=>
  array(4) {
    [0]=>
    string(6) "666666"
    [1]=>
    string(6) "666666"
    [2]=>
    string(6) "666666"
    [3]=>
    string(6) "666666"
  }
}

我想构建数组,以便它看起来像这样,但我不知道该怎么做?

array(1) {
  [0]=>
  array(8) {
    [0]=>
    string(6) "04ba2c"
    [1]=>
    string(6) "666666"
    [2]=>
    string(6) "f4a204"
    [3]=>
    string(6) "666666"
    [4]=>
    string(6) "d40604"
    [5]=>
    string(6) "666666"
    [6]=>
    string(6) "990000"
    [7]=>
    string(6) "666666"
  }

有任何想法可以在PHP中轻松完成吗?

4 个答案:

答案 0 :(得分:2)

for ($i = 0, $len = count($array[0]); $i < $len; ++$i) {
    $result[] = $array[0][$i];
    $result[] = $array[1][$i];
}

或者,如果两个数组的长度不相等,则可以循环直到达到最高值并仅添加找到的项目:

for ($i = 0, $len = max(count($array[0]), count($array[1])); $i < $len; ++$i) {
    if (isset($array[0][$i])) $result[] = $array[0][$i];
    if (isset($array[1][$i])) $result[] = $array[1][$i];
}

答案 1 :(得分:2)

假设$arr[0]$arr[1]长度相等:

$arr2 = array(); 

foreach($arr[0] as $key=>$val) {
    $arr2[] = $arr[0][$key];
    $arr2[] = $arr[1][$key];
}

答案 2 :(得分:0)

$newarray = array();
$len = max(count($array[0]), count($array[1]));
for ($x = 0; $x < $len; $x++) {
   if (isset($array[0][$x])) {
      $newarray[] = $array[0][$x];
   }
   if (isset($array[1][$x])) {
      $newarray[] = $array[1][$x];
   }
}

答案 3 :(得分:0)

$arr = array (
    array("04ba2c","f4a204","d40604","990000"),
    array("666666","666666","666666","666666"),
);
$newArr = array();
array_map(function($a,$b) use(&$newArr) {
    $newArr[0][]=$a;$newArr[0][]=$b;
}, $arr[0], $arr[1]);
print_r($newArr);
/*
Array
(
    [0] => Array
        (
            [0] => 04ba2c
            [1] => 666666
            [2] => f4a204
            [3] => 666666
            [4] => d40604
            [5] => 666666
            [6] => 990000
            [7] => 666666
        )

)
*/