shan
shan

Reputation: 67

how we fill missing values with one array to another on the basis of index

Hello sir below is my multidimensional array that contain some missing values on specific index

$array1 = Array ( [2] => Array ( [1] => 2 [2] => 4 [3] => 9 )

[3] => Array
    (
        [1] => 4
        [2] => 6
        [3] => 
    )

[4] => Array
    (
        [1] => 4
        [2] => 6
        [3] => 7
    )

[5] => Array
    (
        [1] => 2
        [2] => 4
        [3] => 
    )

)

and below is my second array I want to put the array2 value of index 3 and 4 in to the $array1 index 3 and 4 .but i dnt want to replace whole array value. I just want to replace the those value that are null in the $array1

$array2 = Array ( [3] => Array ( [1] => 2 [2] => 4 [3] => 9 )

[5] => Array
    (
        [1] => 4
        [2] => 6
        [3] => 7
    )

)

Required output below where i show the replace value in single qoutes )

$array1 = Array ( [2] => Array ( [1] => 2 [2] => 4 [3] => 9 )

[3] => Array
    (
        [1] => 4
        [2] => 6
        [3] =>  '9'
    )

[4] => Array
    (
        [1] => 4
        [2] => 6
        [3] => 7
    )

[5] => Array
    (
        [1] => 2
        [2] => 4
        [3] =>   '7'
    )

Upvotes: 1

Views: 243

Answers (1)

Murad Hasan
Murad Hasan

Reputation: 9583

This is it:

$array1 = array("2"=> array("1"=>"2", "2"=>"4", "3"=>"9"),
                "3"=> array("1"=>"4", "2"=>"6", "3"=>""),
                "4"=> array("1"=>"4", "2"=>"6", "3"=>"7"),
                "5"=> array("1"=>"2", "2"=>"4", "3"=>"")
                );

$array2 = array("3"=> array("1"=>"2", "2"=>"4", "3"=>"9"),
                "5"=> array("1"=>"4", "2"=>"6", "3"=>"7")
                );

foreach ($array1 as $key => $value) {
    foreach ($value as $key2 => $value2) {
        if($value2 == ""){
            $array1[$key][$key2] = $array2[$key][$key2];
        }
    }
}
echo '<pre>';
print_r($array1);
echo '</pre>';

Output:

Array
(
    [2] => Array
        (
            [1] => 2
            [2] => 4
            [3] => 9
        )

    [3] => Array
        (
            [1] => 4
            [2] => 6
            [3] => 9
        )

    [4] => Array
        (
            [1] => 4
            [2] => 6
            [3] => 7
        )

    [5] => Array
        (
            [1] => 2
            [2] => 4
            [3] => 7
        )

)

Upvotes: 1

Related Questions