LukeKov
LukeKov

Reputation: 63

Merge two arrays by key and append value form one array to other

I have two arrays. Each array have key "test1" and "test2" for example:

$array = [
   "test1" => [
        'value' => 1, 
        "date"=> '2019-01-01'
    ], 
    "test2" => [
        'value' => 2, 
        "date"=> '2019-01-01'
    ]
];
$array2 = [
    "test1" => [
        'value' => 3, 
        "date"=> '2018-01-01'
    ], 
    "test2" => [
        'value' => 4, 
        "date"=> '2018-01-01'
    ]
];

All I need is merge these arrays in way let me output like this:

$finalArray = [
    "test1" => [
        [
            'value' => 1, 
            "date"=> '2019-01-01'
        ], 
        [
            'value' => 3, 
            "date"=> '2018-01-01'
        ]
    ],
    "test2" => [
        [
            'value' => 2, 
            "date"=> '2019-01-01'
        ],
        [
            'value' => 4, 
            "date"=> '2018-01-01'
        ]
    ]
];

It find key from first array and add to this key value from other array on the same key.

Array merge not works for me because it overwrite my keys. Can I do this without foreach on both tables and checking key? Is maybe one method which can do this?

Upvotes: 0

Views: 378

Answers (1)

dWinder
dWinder

Reputation: 11642

You can do that with array_map (documentation):

$res = array_map(null, $array1, $array2);

Notice for the null passed as callback:

NULL can be passed as a value to callback to perform a zip operation on multiple arrays

Live example 3v4l.

Notice this will remove the original keys. You can return them by array_combine and array_keys as:

$res = array_map(null, $array1, $array2);
$res = array_combine(array_keys($array1), $res);

Upvotes: 1

Related Questions