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])
ORarray_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) )
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.
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.
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" );
The count() function returns the number of elements in an array.
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]);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With