You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何判断数组中是否存在同时匹配两个指定键值对的元素

实现方案

方案1:foreach遍历实现(全版本兼容、性能最优)

直接遍历数组做匹配校验,找到符合条件的元素就立刻返回结果,不会遍历剩余内容,性能最优,还可以封装成通用函数支持任意数量的键值匹配:

/**
 * 数组多键值匹配校验
 * @param array $array 待校验的数组
 * @param array $conditions 匹配条件,键值对格式
 * @return bool 是否存在符合条件的元素
 */
function array_multi_match(array $array, array $conditions): bool
{
    foreach ($array as $item) {
        // 统一转为数组处理,兼容元素是对象/数组的场景
        $item = (array)$item;
        $isMatch = true;
        foreach ($conditions as $key => $expectValue) {
            if (!isset($item[$key]) || $item[$key] != $expectValue) {
                $isMatch = false;
                break;
            }
        }
        if ($isMatch) {
            return true;
        }
    }
    return false;
}

调用示例:

// 原数组修正语法后的示例
$arr = [
    (object)[
        "ID" => "10",
        "date" => "04/22/20"
    ],
    (object)[
        "ID" => "20",
        "date" => "05/25/20"
    ],
    (object)[
        "ID" => "32",
        "date" => "07/13/20"
    ]
];

// 传入多条件校验
$result = array_multi_match($arr, [
    'ID' => '32',
    'date' => '07/13/20'
]);
var_dump($result); // 输出bool(true)

方案2:array_filter实现(代码简洁,适合小数组)

如果数组体量不大,可以用array_filter简化代码:

$conditions = [
    'ID' => '32',
    'date' => '07/13/20'
];
$matchedItems = array_filter($arr, function($item) use ($conditions) {
    $item = (array)$item;
    foreach ($conditions as $k => $v) {
        if (!isset($item[$k]) || $item[$k] != $v) {
            return false;
        }
    }
    return true;
});
$result = !empty($matchedItems);

方案3:PHP8.2+专属array_any实现

PHP8.2新增了array_any内置函数,匹配到符合条件的元素就会终止遍历,性能接近手写foreach:

$conditions = [
    'ID' => '32',
    'date' => '07/13/20'
];
$result = array_any($arr, function($item) use ($conditions) {
    $item = (array)$item;
    foreach ($conditions as $k => $v) {
        if (!isset($item[$k]) || $item[$k] != $v) {
            return false;
        }
    }
    return true;
});

内容的提问来源于stack exchange,提问作者Blitzkriegfest

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 02:24:05