PHP比较和更改多维数组中的某些元素 [英] PHP Compare and change certain elements in multidimensional arrays
本文介绍了PHP比较和更改多维数组中的某些元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
简而言之,我有两个简单的数组,我想验证第二个数组中的某些键是否为空值,并将它们替换为第一个数组中的对应值。
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.
示例:
$a1 = [ 1 => 'one', 2 => 'two', 3 => 'three',5=>'cinco', 6=>'six'];
$a2 = [ 2 => 'two', 5=>'five', 6=>'' ];
结果:
Array
(
[2] => two
[5] => five
[6] => six
)
以下代码已对此有效。
$keys = array_keys($a1);
foreach ($keys as $k)
{
if ((isset($a2[$k])) && (($a2[$k]) == '')) {
$a2[$k] = $a1[$k];
}
}
print_r($a2);
但是如果我们想将其应用于两个2D数组怎么办?在这种情况下,正确的方法是什么?假设这两个2D数组将是:
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",
)
);
期望:
$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!
推荐答案
您已经在数据中添加了另一个级别,因此您也可以使用第二个 foreach
循环:
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;
}
}
}
这篇关于PHP比较和更改多维数组中的某些元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文