合并多维数组

时间:2014-05-27 07:23:53

标签: php multidimensional-array

我有一个如下所示的数组: 获取数组需要将数组转换为与0相同的键值

        foreach($array as $key=>$id){               

            $consumer_data[]=$this->App_model->get_session($id);
        }

        print_r($consumer_data);

Array
(
[0] => Array
    (
        [0] => Array
            (
                [ConsumerID] => 1
                [name] => asdfd
            )

        [1] => Array
            (
                [ConsumerID] => 5
                [name] => test
            )

        [2] => Array
            (
                [ConsumerID] => 3
                [name] => test1
            )

    )

[1] => Array
    (
        [0] => Array
            (
                [ConsumerID] => 4
                [name] => test4
            )

    )

我想在与0

相同的键值中实现这样的数组
 Array
(
[0] => Array
    (
        [0] => Array
            (
                [ConsumerID] => 1
                [name] => asdfd
            )

        [1] => Array
            (
                [ConsumerID] => 5
                [name] => test
            )

        [2] => Array
            (
                [ConsumerID] => 3
                [name] => test1
            )
       [3] => Array
            (
                [ConsumerID] => 4
                [name] => test4
            )


    )

我正在使用PHP。谁能指出我应该如何做到这一点的好起点?

4 个答案:

答案 0 :(得分:1)

最简单的解决方案是:

$input = array(
    array(
        array('ConsumerID' => 1, 'name' => 'asdfd'),
        array('ConsumerID' => 5, 'name' => 'test'),
        array('ConsumerID' => 4, 'name' => 'test1'),
    ),
    array(
        array('ConsumerID' => 4, 'name' => 'test4'),
    ),
);
$output = array(
    array()
);

foreach ($input as $data) {
    $output[0] = array_merge($output[0], $data);
}

答案 1 :(得分:1)

您可以使用array_merge()

$new_array[0] = array_merge($array[0], $array[1]);

$array是第一个数组。

SEE DEMO

以获得更具动态性的方法:

$new_array = array(0 => array());
foreach($array as $a) {
    $new_array[0] = array_merge($new_array[0], $a);
}

SEE DEMO 2

答案 2 :(得分:0)

试试这个 - >

 $newArray = array();
  foreach($values as $key=>$val){
      $newArray [0][$key]=$val;

  }
  print_r($newArray);

答案 3 :(得分:0)

检查一下:

<?php
$arr[0] = array(0 => array("ConsumerID" => 1, "name" => "Ni"), 1 => array("ConsumerID" => 2, "name" => "Ab")); 
$arr[1] = array(1 => array("ConsumerID" =>5, "name" => "GE"), 1 => array("ConsumerID" => 6, "name" => "DB"));  

$new = array();

foreach($arr as $key => $value) {


        foreach($value as $innerkey => $innervalue) {

                $new[0][] = $innervalue;

        }
}


print_r($new);
?>