如何在PHP中将多维数组展平(压缩)成一维数组?

时间:2015-10-03 01:29:44

标签: php arrays multidimensional-array type-conversion associative-array

我有这个阵列。我希望所有其他3个阵列都进入这个[0] =>阵列。不希望唯一值只想将所有数组合并为[0] =>阵列。

Array
 (
  [0] => Array
    (
        [0] => Array
            (
                [Campaign] => xxx
                [Phone] => 111
                [State] => cd
            )

         )

 [1] => Array
    (
        [0] => Array
            (
                [Campaign] => zxxxzx
                [Phone] => 111111
                [State] => zxxx
            )

         )

  [2] => Array
    (
        [0] => Array
            (
                [Campaign] => aaaa
                [Phone] => 111
                [State] => Csd
            )

        )

  [3] => Array
    (
        [0] => Array
            (
                [Campaign] => sasa
                [Phone] => 111
                [State] => asas
            )

          )
)

4 个答案:

答案 0 :(得分:1)

这是命名的重要性的另一个例子。你正在使用的基本上是:

$recordsGroups = array(
    // first group:
    array(
        // record 1:
        array(
            'key1' => 'val1',
            'key2' => 'val2',
        ),
        // record 2:
        array(
            'key1' => 'aaa',
            'key2' => 'bbb',
        ),
    ),
    // 2nd group:
    array(
        // record 3:
        array(
            'key1' => 'ccc',
            'key2' => 'ddd',
        ),
    ),
);

你可能想要做的是:

$records = array();
foreach ($recordsGroups as $group)
    foreach ($group as $record)
        $records[] = $record;

哪个会给你:

$records = array(
    // record 1:
    array(
        'key1' => 'val1',
        'key2' => 'val2',
    ),
    // record 2:
    array(
        'key1' => 'aaa',
        'key2' => 'bbb',
    ),
    // record 3:
    array(
        'key1' => 'ccc',
        'key2' => 'ddd',
    ),
);

答案 1 :(得分:0)

这应该做得很好:

$array = call_user_func_array('array_merge', $array);

答案 2 :(得分:0)

因为数组不能有重复的键,所以这个多维数组可以压缩的最好的是关联数组的索引数组。 array_column()将快速完成此任务。

代码:(Demo

$array=[
    [
        ['Campaign'=>'xxx','Phone'=>'111','State'=>'cd']
    ],
    [
        ['Campaign'=>'zxxxzx','Phone'=>'111111','State'=>'zxxx']
    ],
    [
        ['Campaign'=>'aaaa','Phone'=>'111','State'=>'Csd']
    ],
    [
        ['Campaign'=>'sasa','Phone'=>'111','State'=>'asas']
    ]
];

var_export(array_column($array,0));

输出:

array (
  0 => 
  array (
    'Campaign' => 'xxx',
    'Phone' => '111',
    'State' => 'cd',
  ),
  1 => 
  array (
    'Campaign' => 'zxxxzx',
    'Phone' => '111111',
    'State' => 'zxxx',
  ),
  2 => 
  array (
    'Campaign' => 'aaaa',
    'Phone' => '111',
    'State' => 'Csd',
  ),
  3 => 
  array (
    'Campaign' => 'sasa',
    'Phone' => '111',
    'State' => 'asas',
  ),
)

答案 3 :(得分:-2)

您可以创建一个新数组并将数组放入其中。

$newArray = array($oldArray[0][0], $oldArray[1][0], $oldArray[2][0], $oldArray[3][0]);