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条)

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真