Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - How to merge arrays inside array

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
array_merge_recursive(from: $result[0], to : $result[count($result) -1])


Where $result is an array with multiple arrays inside it like this :

$result = Array( 0 => array(),//associative array 1 => array(),//associative array 2 => array(),//associative array 3 => array()//associative array ) 

My Result is :

$result = Array(     0 => Array(         "name" => "Name",         "events" => 1,         "types" => 2     ),     1 => Array(         "name" => "Name",         "events" => 1,         "types" => 3     ),     2 => Array(         "name" => "Name",         "events" => 1,         "types" => 4     ),     3 => Array(         "name" => "Name",         "events" => 2,         "types" => 2     ),     4 => Array(         "name" => "Name",         "events" => 3,         "types" => 2     ) ) 

And what I need is

$result = Array( "name" => "name", "events" => array(1,2,3), "types" => array(2,3,4) ) 
like image 679
Lekhnath Avatar asked Jun 11 '13 09:06

Lekhnath


People also ask

How do I combine two arrays into a new array?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.

How do you merge multidimensional arrays?

The array_merge_recursive() function merges one or more arrays into one array. The difference between this function and the array_merge() function is when two or more array elements have the same key. Instead of override the keys, the array_merge_recursive() function makes the value as an array.

How can I append an array to another array in PHP?

Given two array arr1 and arr2 and the task is to append one array to another array. Using array_merge function: This function returns a new array after merging the two arrays. $arr1 = array ( "Geeks" , "g4g" );

Which function returns the number of elements in an array?

The count() function returns the number of elements in an array.


1 Answers

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.

like image 195
complex857 Avatar answered Sep 27 '22 22:09

complex857