Thursday, 30 August 2018

Merge array with the same keys, array_merge does not work well

I have arrays with the same key like this:

Array1(
    [00] => green
    [10] => red
    [20] => yellow
)

Array2(
    [00] => avocado
    [10] => apple
    [20] => banana
)

I want this:
Array_result(
    [00] => Array(
            [0] => green
            [1] => avocado
        )

    [10] => Array(
            [0] => red
            [1] => apple
        )

    [20] => Array(
            [0] => yellow
            [1] => banana
        ))

Or [0], [1], [2], I do not mind the key, I try array_merge but it doesn't work fine.
EDIT: I don't know why, but array_merge_recursive prints this:
Array
(
    [00] => Array
        (
            [0] => green
            [1] => avocado
        )

    [0] => red
    [1] => apple
    [2] => yellow
    [3] => banana
)


You are looking for array_merge_recursive instead of array_merge.
<?php
$A = Array(00 => "green", 10 => "red", 20 => "yellow");
$B = Array(00 => "avocado", 10 => "apple", 20 => "banana");

$result = array_merge_recursive($A, $B);

print_r($result);?>

0 comments:

Post a Comment