我有两个数组。当元素包含在第二个数组中时,我需要从第一个数组中删除一个元素。
例如:
$First = array("apple"=>"7", "orange"=>"8", "strawberry"=>"9", "lemon"=>"10", "banana"=>"11");
$Second = array("orange"=>"1", "lemon"=>"1","banana"=>"1");
$Result = array("apple"=>"7","strawberry"=>"9");
我使用了以下代码,但它无效:
foreach($Second as $key){
$keyToDelete = array_search($key, $First);
unset($First[$keyToDelete]);
}
print_r($First);
答案 0 :(得分:7)
使用array_diff_key
- http://php.net/manual/en/function.array-diff-key.php
$First = array("apple"=>"7", "orange"=>"8", "strawberry"=>"9", "lemon"=>"10", "banana"=>"11");
$Second = array("orange"=>"1", "lemon"=>"1","banana"=>"1");
$Result = array_diff_key($First, $Second);
答案 1 :(得分:2)
你关闭了!
首先,
foreach ($Second as $key)
只会给你价值。获得你必须要做的钥匙
foreach ($Second as $key => $value)
循环遍历$ Second数组,然后如果它们在$ First数组中存在(使用isset
),则使用unset
删除它。 $ Second将与$ Results
foreach ($Second as $key => $value) {
if (isset($First[$key])) {
unset($First[$key]);
}
}
或者,如果您想保留$ First和$ Second,那么您可以执行以下操作:
foreach ($Second as $key => $value) {
if (!isset($First[$key])) {
$Results[$key] = $value;
}
}