Search code examples
phparraysarray-map

Merge multidimensional array preserving keys


I have three arrays as follows:

Array
(
    [1000] => Item 0
    [1001] => Item 1
    [1002] => Item 2
)

Array
(

    [1000] => £35.00
    [1001] => £60.00
    [1002] => £24.00
)
Array
(
    [1000] => 1
    [1001] => 2
    [1002] => 3
)

I need to merge these three arrays preserving the keys as follows:

Array
(
    [1000] => Array
                (
                    [0] => Item 0
                    [1] => £35.00
                    [2] => 1
                )
    [1001] => Array
                (
                    [0] => Item 1
                    [1] => £60.00
                    [2] => 2
                )
    [1002] => Array
                (
                    [0] => Item 2
                    [1] => £24.00
                    [2] => 3
                )
)

array_map(null, array1, array2, array3) solves it to some level but doesn't preserves the keys. How can it be done?


Solution

  • You could wrap your array_map together with an array_keys() against your original array within an array_combine()

    $array1 = array(
        1000 => 'Item 0',
        1001 => 'Item 1',
        1002 => 'Item 2',
    );
    $array2 = array(
        1000 => '£35.00',
        1001 => '£60.00',
        1002 => '£24.00',
    );
    $array3 = array(
        1000 => 1,
        1001 => 2,
        1002 => 3,
    );
    
    $result = array_combine(
        array_keys($array1),
        array_map(null, $array1, $array2, $array3)
    );
    var_dump($result);