PHP - How to merge arrays inside array

前端 未结 4 1639
灰色年华
灰色年华 2020-11-27 04:24

How to merge n number of array in php. I mean how can I do the job like :
array_merge(from : $result[0], to : $result[count($result)-1])
OR<

4条回答
  •  死守一世寂寞
    2020-11-27 04:44

    array_merge can take variable number of arguments, so with a little call_user_func_array trickery you can pass your $result array to it:

    $merged = call_user_func_array('array_merge', $result);
    

    This basically run like if you would have typed:

    $merged = array_merge($result[0], $result[1], .... $result[n]);
    

    Update:

    Now with 5.6, we have the ... operator to unpack arrays to arguments, so you can:

    $merged = array_merge(...$result);
    

    And have the same results. *

    * The same results as long you have integer keys in the unpacked array, otherwise you'll get an E_RECOVERABLE_ERROR : type 4096 -- Cannot unpack array with string keys error.

提交回复
热议问题