生命之风的低语
Whispers in the Wind of Life.

在二维数组中判断键值是否存在的PHP函数封装

秀秀 发布于 2024-6-19 10:58    23 次阅读

在 PHP 中,要判断某个键值是否存在于二维数组中,可以使用以下方法:

  1. 使用 array_column 提取所有子数组中的键值,然后使用 in_array 检查值是否存在。
  2. 遍历二维数组,并使用 issetarray_key_exists 检查键值。

下面是这两种方法的示例:

方法一:使用 array_columnin_array

假设我们有一个二维数组 $array,要检查键值是否存在,可以使用如下代码:

$array = [
    ['id' => 1, 'name' => 'John'],
    ['id' => 2, 'name' => 'Jane'],
    ['id' => 3, 'name' => 'Doe'],
];

$key = 'id';
$value = 2;

$column = array_column($array, $key);

if (in_array($value, $column)) {
    echo "The value $value exists for the key $key in the array.";
} else {
    echo "The value $value does not exist for the key $key in the array.";
}

方法二:遍历数组并检查键值

这是一种更直接的方法,遍历数组并检查每个子数组中的键值:

$array = [
    ['id' => 1, 'name' => 'John'],
    ['id' => 2, 'name' => 'Jane'],
    ['id' => 3, 'name' => 'Doe'],
];

$key = 'id';
$value = 2;
$exists = false;

foreach ($array as $subArray) {
    if (isset($subArray[$key]) && $subArray[$key] == $value) {
        $exists = true;
        break;
    }
}

if ($exists) {
    echo "The value $value exists for the key $key in the array.";
} else {
    echo "The value $value does not exist for the key $key in the array.";
}

这两种方法都可以有效地检查二维数组中某个键值是否存在,具体使用哪种方法取决于你的需求和代码风格偏好。

下面我们将上述检查逻辑封装成一个方法,这样在需要时可以直接调用。以下是一个封装好的方法:

function keyValueExistsInArray($array, $key, $value) {
    foreach ($array as $subArray) {
        if (isset($subArray[$key]) && $subArray[$key] == $value) {
            return true;
        }
    }
    return false;
}

// 示例使用
$array = [
    ['id' => 1, 'name' => 'John'],
    ['id' => 2, 'name' => 'Jane'],
    ['id' => 3, 'name' => 'Doe'],
];

$key = 'id';
$value = 2;

if (keyValueExistsInArray($array, $key, $value)) {
    echo "The value $value exists for the key $key in the array.";
} else {
    echo "The value $value does not exist for the key $key in the array.";
}

解释:

  1. 函数定义

    • keyValueExistsInArray 函数接受三个参数:$array(二维数组),$key(要查找的键),和 $value(要匹配的值)。
  2. 遍历逻辑

    • 使用 foreach 循环遍历 $array 中的每个子数组。
    • 使用 isset 检查当前子数组是否包含指定的键,并比较键值是否匹配。
  3. 返回值

    • 如果找到匹配的键值,函数返回 true
    • 如果遍历完所有子数组都未找到匹配,函数返回 false

这样,你可以在其他代码中方便地调用 keyValueExistsInArray 函数来检查特定键值对是否存在。