将嵌套数组转换为单维数组

时间:2016-08-10 07:47:16

标签: php

我有一个数组:

Array
(
    [0] => Array
        (
            [2010] => 2010
        )

    [1] => Array
        (
            [2011] => 2011
        )

    [2] => Array
        (
            [2012] => 2012
        )

    [3] => Array
        (
            [2013] => 2013
        )

    [4] => Array
        (
            [2014] => 2014
        )

    [5] => Array
        (
            [2015] => 2015
        )

    [6] => Array
        (
            [2016] => 2016
        )

)

我要将其转换为

array(
[2010] => 2010
[2011] => 2011
[2012] => 2012
)

我写了这样一个函数:

foreach($arr as $a)
{
   foreach($a as $k=>$sub)
   {
      $newArr[$k] = $sub;
   }
}

我做得对吗?

3 个答案:

答案 0 :(得分:1)

请记住What's the difference between array_merge and array + array?

在“endresult”数组上使用+ =将给定数组添加到当前数组中。如上面的链接所述,有一些注意事项要注意重叠键的情况。

$arr = [[2012 => 'foo'],[2014 => 'bar'],[2015=>'baz']];
$new = [];
foreach($arr as $i) {
  $new += $i;
}
echo "<PRE>";
var_dump($new);

现场样本:https://ideone.com/olydNq

答案 1 :(得分:0)

请尝试此

$array = Array
(
    '0' => Array
        (
            '2010' => 2010,
        ),

    '1' => Array
        (
            '2011' => 2011,
        ),

    '2' => Array
        (
            '2012' => 2012,
        ),

    '3' => Array
        (
            '2013' => 2013,
        ),

    '4' => Array
        (
            '2014' => 2014,
        ),

    '5' => Array
        (
            '2015' => 2015,
        ),

    '6' => Array
        (
            '2016' => 2016,
        ),

);

$oneDimensionalArray = call_user_func_array('array_merge', $array);
foreach($oneDimensionalArray as $_oneDimensionalArray)
{
     $newArr[$_oneDimensionalArray] = $_oneDimensionalArray;
}   
print_r($newArr)

答案 2 :(得分:0)

请检查此代码,它也适用于未配置的数组结构

<?php
$array = array
(
    'aaaaa',
    10,
    '0' => array
        (
            '2010' => 2010,
        ),

    '1' => array
        (
            '2011' => 2011,
        ),

    '2' => array
        (
            '2012' => 2012,
        ),

    '3' => array
        (
            '2013' => 2013,
        ),

    '4' => array
        (
            '2014' => 2014,
        ),

    '5' => array
        (
            '2015' => 2015,
        ),

    '6' => array
        (
            '2016' => 2016,
            '2017' => 2017,
            'xxxx' => 'yyyy',
        ),

);



$newArr=array();



function walk_first($val, $key)
{
    if(is_array($val))
    {
    array_walk($val, 'walk_second');
    }
}
function walk_second($val, $key)
{
    global $newArr;
    $newArr[$key]=$val;
}
array_walk($array, 'walk_first');

print_r($newArr);
?>