I have two arrays (one simple and one multidimensional) and I want to verify if certain keys from the multidimensional array have empty values and replace them with their correspondent values from the simple array.
Solution for both simple arrays and/or 2D arrays is here:
PHP Compare and change certain elements in multidimensional arrays
But what would be the solution in the situation above?
Example of simple array:
$superheroes_complete = array(
1 => 'one',
'two' => 'two',
3 => 'three',
'email' => 'peterparker@mail.com',
5 => 'cinco',
6 => 'six',
'name' => 'Clark Kent',
8 => 'eight'
);
Example of multidimensional array:
$superheroes_empty = array(
"spiderman" => array(
"name" => "Peter Parker",
"email" => "",
),
"superman" => array(
"name" => "",
"email" => "clarkkent@mail.com",
),
"ironman" => array(
"name" => "Harry Potter",
"email" => "harrypotter@mail.com",
)
);
Expectation:
$superheroes_empty = 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",
)
);
Thank you in advance.
Here is one way to do this using array_walk_recursive
:
array_walk_recursive($superheroes_empty, function(&$v, $k) use ($superheroes_complete) {
if ($v === '' && isset($superheroes_complete[$k])) {
$v = $superheroes_complete[$k];
}
});
This will fill in any empty values if a corresponding key is found in $superheroes_complete
. Since this makes replacements by reference, it will directly change the $superheroes_empty
array, so if you still need the one with empty values, make a copy before using this.
You can also use this
foreach($superheroes_empty as $key =>$array){
foreach($array as $key1=>$data){
if(empty($data)){
$superheroes_empty[$key][$key1] = $superheroes_complete[$key1];
}
}
}
echo "<pre>";print_r($superheroes_empty);