Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging 3 arrays in PHP

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.

like image 208
tenten Avatar asked Jul 18 '17 11:07

tenten


People also ask

What are the 3 types of PHP arrays?

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.

How do you merge 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.


1 Answers

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);
like image 86
Ali Faris Avatar answered Sep 18 '22 17:09

Ali Faris