dongtang8678 2019-01-22 11:08
浏览 57
已采纳

重复并合并PHP数组

With array_fill, I want to repeat and merge array.

Example, when I execute :

$array = array_fill(0, 2, array_merge(
   ['hello'],
   ['by']
));

var_dump($array);

I have this result :

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "hello"
    [1]=>
    string(2) "by"
  }
  [1]=>
  array(2) {
    [0]=>
    string(5) "hello"
    [1]=>
    string(2) "by"
  }
}

But I want this result :

array(4) {
    [0]=>
    string(5) "hello"
    [1]=>
    string(2) "by"
    [2]=>
    string(5) "hello"
    [3]=>
    string(2) "by"
}
  • 写回答

3条回答 默认 最新

  • duangong0690 2019-01-22 11:30
    关注

    Add one more step - merge all these arrays into one:

    $array = array_merge(...array_fill(0, 2, array_merge(
       ['hello'],
       ['by']
    )));
    

    Here I used a variadic function argument syntax. If your php version (older than php5.6) doesn't support it, use call_user_func_array:

    $array = call_user_func_array('array_merge', array_fill(0, 2, array_merge(
       ['hello'],
       ['by']
    )));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 需求高精度PT100设计电路和算法
  • ¥15 单片机配网,继电器开关,广播
  • ¥60 Qcustomplot绘制实时动态曲线
  • ¥20 运用matlab画x-y图
  • ¥15 用idea运行项目,运行tomcat报错:断言失败
  • ¥15 Sqlserver查询链接服务器数据问题
  • ¥15 Bibtex4Word 引用中文文献
  • ¥20 用opencv c/c++ 转换成灰度图,然后做一下直方图均衡,输出mp4文件
  • ¥20 matlab中的双层数值积分
  • ¥50 服务器打印水晶报表问题