简而言之,我有两个简单的数组,我想验证第二个数组中的某些键是否具有空值,并将它们替换为第一个数组中的对应值。
示例:
$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);
但是如果我们想将其应用于两个二维数组怎么办?在这种情况下,正确的方法是什么?假设这两个二维数组是:
$superheroes_complete = array(
"spiderman" => array(
"name" => "Peter Parker",
"email" => "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92e2f7e6f7e0e2f3e0f9f7e0d2fff3fbfebcf1fdff" rel="noreferrer noopener nofollow">[email protected]</a>",
),
"superman" => array(
"name" => "Clark Kent",
"email" => "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="51323d30233a3a343f25113c30383d7f323e3c" rel="noreferrer noopener nofollow">[email protected]</a>",
),
"ironman" => array(
"name" => "Harry Potter",
"email" => "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3bbb2a1a1aaa3bca7a7b6a193beb2babffdb0bcbe" rel="noreferrer noopener nofollow">[email protected]</a>",
)
);
$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" => "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="acdcc9d8c9dedccddec7c9deecc1cdc5c082cfc3c1" rel="noreferrer noopener nofollow">[email protected]</a>",
),
"super-man" => array(
"name" => "Clark Kent",
"email" => "something",
),
"iron-man" => array(
"name" => "Harry Potter",
"email" => "another one",
)
);
非常感谢并提前感谢您!
最佳答案
您已经向数据添加了另一个级别,因此您也可以使用第二个 foreach
循环向检查添加另一个级别:
foreach ($superheroes_complete as $hero => $info) {
foreach ($info as $key => $value) {
if (empty($superheroes_empty[$hero][$key])) {
$superheroes_empty[$hero][$key] = $value;
}
}
}
关于PHP 比较和更改多维数组中的某些元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38275940/