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

报告相同问题?