Search code examples
phparraysmultidimensional-arraymapping

Use a flat mapping array to convert another flat array into a 2d array


I have 2 arrays

$arr1 = Array
    (
        [REG1] => 94
        [REG3] => 45
    )

$arr2 =Array
    (
        [0] => REG1
        [1] => REG2
        [2] => REG3
        [3] => REG4
    )

I have to loop 2 arrays and I would like a result in one array like this:

Array(
    [0] => Array(
            [REG1] => 94
        )
    [1] => Array(
            [REG2] =>
        )
    [2] => Array(
            [REG3] => 45
        )
    [3] => Array(
            [REG4] => 
        )
)

But for the instand I can not do what I want, here is where I am:

private function mergeData($arr1, $arr2){

    $result = array_map(function($v1, $v2){
        $t[$v1] = $v2;
        return $t;
    }, $arr2, $arr1);
                
    return $result;
}

output:

Array(
    [0] => Array(
           [REG1] => 94
        )
    [1] => Array(
            [REG2] =>45
        )
    [2] => Array(
            [REG3] => 
        )
    [3] => Array(
            [REG4] => 
        )
)

I cannot correctly put the first array's values with the right keys. I tried with array_merge_recursive(), but also failed.


Solution

  • Another option would be to use the array_map function and map key with the corresponding values, if any:

    $arr1 = [
        'REG1' => 94,
        'REG3' => 45
    ];
    
    $arr2 = [
        'REG1',
        'REG2',
        'REG3',
        'REG4'
    ];
    
    $result = array_map(function($item) use($arr1){
        return [$item => isset($arr1[$item]) ? $arr1[$item] : ""];
    },$arr2);
    

    This will return:

    Array
    (
        [0] => Array
            (
                [REG1] => 94
            )
    
        [1] => Array
            (
                [REG2] => 
            )
    
        [2] => Array
            (
                [REG3] => 45
            )
    
        [3] => Array
            (
                [REG4] => 
            )
    
    )