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)
)
If you would like to:
You can use this function:
Let's see it in action.. here's some data:
Simple structure: Pure array of arrays to merge.
Less simple: Array of arrays, but would like to specify the people and ignore the count.
Run it
Results - Both return this:
Extra Fun: If you want to single out one property in an array or object, like "name" from an array of people objects(or associate arrays), you can use this function
The getter is for possibly protected/private objects.
$namesOnly = getSinglePropFromCollection('name', $peopleResults, false);
returns
Try this
Or, instead of array_merge, you can use the + op which performs a union:
I really liked the answer from complex857 but it didn't work for me, because I had numeric keys in my arrays that I needed to preserve.
I used the
+
operator to preserve the keys (as suggested in PHP array_merge with numerical keys) and usedarray_reduce
to merge the array.So if you want to merge arrays inside an array while preserving numerical keys you can do it as follows:
Result:
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:This basically run like if you would have typed:
Update:
Now with 5.6, we have the
...
operator to unpack arrays to arguments, so you can: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.