doutian3010 2017-07-31 09:55
浏览 45
已采纳

PHP重置没有循环的数组的第一级

I have a simple multidimensional array like the following

$array = array(
    array('key1'=>array('a','b')),
    array('key2'=>array('c','d'), 'key3'=>array('e','f')),
    array('key4'=>array('g','h'), 'key5'=>array('i','j'), 'key6'=>array('k','l', 'm'))
);

and I would reset its first level like the following

$array = array(
    'key1'=>array('a','b'),
    'key2'=>array('c','d'),
    'key3'=>array('e','f'),
    'key4'=>array('g','h'),
    'key5'=>array('i','j'),
    'key6'=>array('k','l','m')
);

I know it's quite easy with a foreach loop to achieve, but I'm wondering if it's possible to do it using one line code.

What I tried so far

array_map('key', $array);

but it returns only the first key of child array.

Any thoughts?

  • 写回答

2条回答 默认 最新

  • douou9094747 2017-07-31 10:17
    关注

    PHP 5.6 introduce the variadic functions in PHP, which allow one to write funtions that take any additional argument into the same array using the splat operator : ... .

    The other - maybe fairly less known - use of that operator is that it works the other way around. By placing that operator before an array in a function's call, it makes that function to take the entries of that array as if you wrote them inline.

    Which allows you to type :

    $array = array_merge(... $array);
    

    Sending $array would usually return $array unchanged. Using the splat makes array_merge to work on the undefined amount of 2nd level arrays in it. Since array_merge is itself a variadic function that merge any arrays you send to it, it works.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?