PHP:如何检查指定数组是否存在于另一个数组中
检查关联数组元素是否存在于数组列表中
嘿,我来帮你搞定这个数组匹配的需求!你需要判断$foods_customer里的食物组合是否完整存在于$foods的组合列表中,对吧?下面是具体的实现方案:
需求回顾
- 当
$foods_customer = array(["meal"=>1,"rice"=>1])(对应格式[{meal: 1, rice: 1}]),$foods = array(["meal"=>1], ["meal"=>1,"rice"=>1])(对应格式[{meal: 1}, {meal: 1, rice: 1}])时,需要返回true - 当
$foods_customer变成array(["meal"=>1,"rice"=>1,"cheese"=>1])时,返回false
解决方案
核心是要严格匹配关联数组的所有键值对,不能只比较部分内容,也不能做松散的类型匹配。这里有两种可靠的实现方式:
方法1:使用in_array严格模式
PHP的in_array函数在开启严格模式(第三个参数设为true)时,会同时检查值的类型和完整的键值对,完美符合我们的需求。
// 定义测试数组 $foods_customer = array(["meal"=>1,"rice"=>1]); $foods = array(["meal"=>1], ["meal"=>1,"rice"=>1]); // 提取要验证的目标组合 $target_food = $foods_customer[0]; // 严格检查是否存在 $is_exists = in_array($target_food, $foods, true); var_dump($is_exists); // 输出:bool(true) // 测试不匹配的场景 $foods_customer_new = array(["meal"=>1,"rice"=>1,"cheese"=>1]); $target_new = $foods_customer_new[0]; $is_exists_new = in_array($target_new, $foods, true); var_dump($is_exists_new); // 输出:bool(false)
方法2:手动遍历比较(更直观)
如果你想更清晰地控制匹配逻辑,可以手动遍历$foods数组,用===严格比较每个元素:
function checkCustomerFoodExists($customer_foods, $foods_list) { // 如果用户的食物组合为空,直接返回false if (empty($customer_foods)) { return false; } $target = $customer_foods[0]; // 遍历所有食物组合逐一匹配 foreach ($foods_list as $food) { if ($food === $target) { return true; } } return false; } // 测试匹配场景 $exists = checkCustomerFoodExists($foods_customer, $foods); var_dump($exists); // bool(true) // 测试不匹配场景 $exists_new = checkCustomerFoodExists($foods_customer_new, $foods); var_dump($exists_new); // bool(false)
关键说明
- 为什么要用严格模式?因为松散比较(比如不设
true参数)会忽略类型差异(比如数字1和字符串"1"会被认为相等),还可能匹配到键值对不全的元素,导致结果不符合预期。 - 关联数组的顺序不影响匹配:PHP在比较两个关联数组时,只要所有键值对都一致,不管键的顺序如何,
===和严格模式的in_array都会认为它们相等。
内容的提问来源于stack exchange,提问作者SaroBeatbox
相关产品推荐
相关产品推荐

