从PHP数组中删除特定的键值对 [英] Remove Specific key value pair from PHP array

查看:639
本文介绍了从PHP数组中删除特定的键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个键值对数组,一个是原始的,另一个是需要删除的键值对数组。我需要删除特定的组合,即$ removeArray将包含:

I have two key value pair arrays, one is the original, the other an array of key value pairs that need to be removed. I need to remove a specific combination, ie $removeArray would contain:

Array([Word] => 78)

我尝试过:

foreach($removeArray as $key => $value){unset($originalArray[$key][$value]);}

这根本不起作用。 我需要根据精确的键值对匹配项来删除。

编辑:

原始

Array ( [distribution] => 25 [watch] => 25 [electricity] => 25 [timepiece] => 8 [wristwatch] => 25 [energy] => 8 [transmission] => 8 [clock] => 16 ) 

删除

Array ( [timepiece] => 8 [energy] => 8 [watch] => 17 ) 

结果

Array ( [distribution] => 25 [watch] => 25 [electricity] => 25 [wristwatch] => 25  [transmission] => 8 [clock] => 16 ) 






注意:


NOTE:

[watch] => 25 不受影响,因为它不等于 [watch] => 17

[watch] => 25 is not affected, because it is not equal to [watch] => 17

推荐答案

您可以使用 array_diff_assoc() ,它同时比较值和键:

You can use array_diff_assoc() for that, that compares both the values and the keys:

$result = array_diff_assoc($original, $to_remove);

示例代码:

$removeArray = array(
    'word'=>45,
    'number'=>112,
    'sign'=>2167
);

$originalArray = array(
    'lorem'=>2343,
    'ipsum'=>433,
    'word'=>78,
    'number'=>112,
    'sign'=>2167
);

$result = array_diff_assoc($originalArray, $removeArray);

结果:

Array
(
    [lorem] => 2343
    [ipsum] => 433
    [word] => 78
)

这篇关于从PHP数组中删除特定的键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆