I have 3 arrays as below.
$array1 = Array
(
[0] => 05/01
[1] => 05/02
)
$array2 =Array
(
[0] => ED
[1] => P
)
$array3 =Array
(
[0] => Mon
[1] => Tue
)
I want to merge these 3 arrays as below $result_array
. I have written a code as below. But It gave a empty array.
$result_array =Array
(
[0] => Array
(
[0] => 05/01
[1] => ED
[2] => Mon
)
[1] => Array
(
[0] => 05/02
[1] => P
[2] => Tue
)
)
Code:
for($z=0; $z<count($array1); $z++){
$all_array[$z][] = array_merge($array1[$z],$array2[$z] );
$all_array2[$z] = array_merge($all_array[$z],$array3[$z] );
}
Please help me to do this.
In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.
To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.
this work for n of arrays and dynamic length of array
function mergeArrays(...$arrays)
{
$length = count($arrays[0]);
$result = [];
for ($i=0;$i<$length;$i++)
{
$temp = [];
foreach ($arrays as $array)
$temp[] = $array[$i];
$result[] = $temp;
}
return $result;
}
$x = mergeArrays(['05/01' , '05/02'] , ['ED' , 'P'] , ['Mon' , 'Tus']);
$y = mergeArrays(['05/01' , '05/02' , 'X'] , ['ED' , 'P' , 'Y'] , ['Mon' , 'Tus' , 'Z'] , ['A' , 'B' , 'C']);
var_dump($x);
var_dump($y);
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