douqilai4263 2018-08-30 20:43
浏览 57
已采纳

array_merge基于整数值

Let's say that I have a variable number variable $num which can contain any interger and I have array $my_array which contains some values like:

$my_array = ['a','b','c'];

I would like to merge another dynamic array $dyn_array with $my_array based on the value of $num for example.

Let's say $num = 2, I would like to have:

$merged_array = array_merge($my_array, $dyn_array, $dyn_array);

If $num = 3, I would like to have:

$merged_array = array_merge($my_array, $dyn_array, $dyn_array, $dyn_array);

So basically adding $dyn_array inside the array_merge depending on the value of $num.

How would I go about doing something like that?

Thanks for any help

  • 写回答

2条回答 默认 最新

  • dongxing1412 2018-08-30 20:49
    关注

    You can use ... (the "splat" operator) to expand the result of a call to array_fill, which will merge as many copies of $dyn_array as you need:

    $num = 2;
    $result = array_merge($my_array, ...array_fill(0, $num, $dyn_array));
    

    See https://3v4l.org/amCJu


    For PHP versions earlier than 5.6, which don't support ..., you can use the following line instead:

    $result = array_reduce(
      array_fill(0, $num, $dyn_array),
      function($carry, $item) { return array_merge($carry, $item); },
      $my_array
    );
    

    which iterates over the same copies from the array_fill call, merging them into the result one at a time. See https://3v4l.org/s7dvd

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

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料