PHP比较键并更改多维数组中的某些值以及简单数组中相应键的值 [英] PHP Compare keys and change certain values from a multidimensional array with corresponding keys' values from a simple array
问题描述
我有两个数组(一个简单的数组和一个多维的数组),我想验证多维数组中的某些键是否具有空值,并用简单数组中的对应值替换它们。
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.
简单数组和/或2D数组的解决方案都在这里:
Solution for both simple arrays and/or 2D arrays is here:
但是在上述情况下解决方案是什么?
But what would be the solution in the situation above?
简单数组示例:
$superheroes_complete = array(
1 => 'one',
'two' => 'two',
3 => 'three',
'email' => 'peterparker@mail.com',
5 => 'cinco',
6 => 'six',
'name' => 'Clark Kent',
8 => 'eight'
);
多维数组示例:
$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",
)
);
期望:
$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",
)
);
谢谢。
推荐答案
这是使用 array_walk_recursive
的一种方法:
array_walk_recursive($superheroes_empty, function(&$v, $k) use ($superheroes_complete) {
if ($v === '' && isset($superheroes_complete[$k])) {
$v = $superheroes_complete[$k];
}
});
如果在 $中找到了对应的键,它将填充任何空值superheroes_complete
。由于这是通过引用进行替换的,因此它将直接更改 $ superheroes_empty
数组,因此,如果您仍然需要带有空值的数组,请在使用该数组之前进行复制。
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.
这篇关于PHP比较键并更改多维数组中的某些值以及简单数组中相应键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!