Alberto Alberto - 4 months ago 6
PHP Question

PHP Compare and change certain elements in multidimensional arrays

To be short, I have two simple arrays and I want to verify if certain keys from the second array have empty values and replace them with their correspondent values from the first array.

Example:

$a1 = [ 1 => 'one', 2 => 'two', 3 => 'three',5=>'cinco', 6=>'six'];
$a2 = [ 2 => 'two', 5=>'five', 6=>'' ];


Result:

Array
(
[2] => two
[5] => five
[6] => six
)


The following code works already for this.

$keys = array_keys($a1);
foreach ($keys as $k)
{
if ((isset($a2[$k])) && (($a2[$k]) == '')) {
$a2[$k] = $a1[$k];
}
}
print_r($a2);


But what if we want to apply this for two 2D arrays? What will be the proper approach in that case? Let's say these two 2D arrays will be:

$superheroes_complete = array(
"spiderman" => array(
"name" => "Peter Parker",
"email" => "peterparker@mail.com",
),
"superman" => array(
"name" => "Clark Kent",
"email" => "clarkkent@mail.com",
),
"ironman" => array(
"name" => "Harry Potter",
"email" => "harrypotter@mail.com",
)
);

$superheroes_empty = array(
"spiderman" => array(
"name" => "Peter Parker",
"email" => "",
),
"superman" => array(
"name" => "Clark Kent",
"email" => "something",
),
"ironman" => array(
"name" => "Harry Potter",
"email" => "another one",
)
);


Expectation:

$superheroes = array(
"spider-man" => array(
"name" => "Peter Parker",
"email" => "peterparker@mail.com",
),
"super-man" => array(
"name" => "Clark Kent",
"email" => "something",
),
"iron-man" => array(
"name" => "Harry Potter",
"email" => "another one",
)
);


Much appreciation and thank you in advance!

Answer

You've added another level to your data, so you can just add another level to your checking as well with a second foreach loop:

foreach ($superheroes_complete as $hero => $info) {
    foreach ($info as $key => $value) {
        if (empty($superheroes_empty[$hero][$key])) {
            $superheroes_empty[$hero][$key] = $value;
        }
    }
}
Comments