Search code examples
phparraysmultidimensional-arrayarray-merge

Array merge with same keys


I have these three arrays:

Array
(
    [1] => [email protected]
    [2] => [email protected]
    [3] => [email protected]
)

Array
(
    [1] => 
    [2] => 4234235
    [3] => 
)

Array
(
    [2] => 1
)

And I want to generate this output:

Array
(
    [1] => array(
            [0] => [email protected]
            )
    [2] => array(
            [0] => [email protected]
            [1] => 4234235
            [2] => 1
            )
    [3] => array(
            [0] => [email protected]
            )
)

I need some assistance because I already researched array_merge_recursive() and array_merge(), but I can't get the correct result.

If I need to use foreach() what must I do to merge these 3 arrays.


Solution

  • Wrote a little script:

    $a = array
    (
        1=>"[email protected]",
        2=>"[email protected]",
        3=>"[email protected]",
    );
    
    $b = array
    (
        2 => 4234235 
    );
    
    $c = array
    (
        2 => 1
    );
    
    $arrayKeys = array_unique(
        array_merge(
            array_keys($a),
            array_keys($b),
            array_keys($c)
        )
    );
    
    $d = array_combine(
        $arrayKeys,
        array_fill(
            0,
            count($arrayKeys),
            array()
        )
    );
    
    foreach($a as $key => $value) {
        if(!empty($a[$key])) {
            $d[$key][] = $a[$key];
        }
        if(!empty($b[$key])) {
            $d[$key][] = $b[$key];
        }
        if(!empty($c[$key])) {
            $d[$key][] = $c[$key];
        }
    }
    var_dump($d);
    

    Also if you want to you can merge together the arrays using the variable names only

    //names of the variables to merge together
    $arrayVariableNames = array("a","b","c");
    
    //merging array keys together
    $arrayKeys = array();
    foreach($arrayVariableNames as $variableName) {
        $arrayKeys = array_merge(
            $arrayKeys,
            array_keys(${$variableName})
        );
    }
    $arrayKeys = array_unique($arrayKeys);
    
    //initialize the result array with empty arrays
    $resultArray = array_combine(
        $arrayKeys,
        array_fill(
            0,
            count($arrayKeys),
            array()
        )
    );
    
    //loop through all the keys and add the elements from all the arrays
    foreach($resultArray as $key => &$value) {
        foreach($arrayVariableNames as $variableName) {
            if(!empty(${$variableName}[$key])) {
                $value[] = ${$variableName}[$key];
            }
        }
    }