检查关联数组是否包含键值对

时间:2014-09-01 16:55:10

标签: php arrays

假设我有一个数组,其元素如下:

$elements = array(
  "Canada" => "Ottawa",
  "France" => "Paris",
  ...
);

如何检查此阵列中是否存在"Canada" => "Ottawa"

3 个答案:

答案 0 :(得分:5)

在文档中查看Array Functions列表,我没有看到内置任何内容来执行此操作。但是很容易为它推出自己的实用功能:

/*
    Returns true if the $key exists in the haystack and its value is $value.

    Otherwise, returns false.
*/
function key_value_pair_exists(array $haystack, $key, $value) {
    return array_key_exists($key, $haystack) &&
           $haystack[$key] == $value;
}

使用示例:

$countries_to_capitals = [
    'Switzerland' => 'Bern',
    'Nepal' => 'Kathmandu',
    'Canada' => 'Ottawa',
    'Australia' => 'Canberra',
    'Egypt' => 'Cairo',
    'Mexico' => 'Mexico City'
];
var_dump(
    key_value_pair_exists($countries_to_capitals, 'Canada', 'Ottawa')
); // true
var_dump(
    key_value_pair_exists($countries_to_capitals, 'Switzerland', 'Geneva')
); // false

答案 1 :(得分:3)

if (isset($elements[$country]) AND $elements[$country] == $capitale) {
    return true;
}
return false;

答案 2 :(得分:0)

我将这些答案中的几个放在一起,得出了这个结论:

// enum dictionary
$QUERYABLE_FIELDS = [
    'accounts' => [ 'phone', 'business_email' ],
    'users' => [ 'email' ],
];

// search terms
$table = 'users';
$column = 'email';
$value = 'alice@bob.com';

if (array_key_exists($table, $QUERYABLE_FIELDS)) {
    if (in_array($column, $QUERYABLE_FIELDS[$table])) {
        // if table and column are allowed, return Boolean if value already exists
        // this is Laravel PHP, but just note that $exists will either be
        // the first matching record, or null
        $exists = DB::table($table)->where($column, $value)->first();

        if ($exists) return response()->json([ 'in_use' => true ], 200);
        return response()->json([ 'in_use' => false ], 200);
    }

    return response()->json([ 'error' => 'Illegal column name: '.$column ], 400);
}

return response()->json([ 'error' => 'Illegal table name: '.$table ], 400);

要进一步细分,如果您的关联数组中包含一些复杂的值,则可以使用array_key_exists()来按名称检查它们。

如果键存在,您可以正常读取其值,如上面的示例所示,为$QUERYABLE_FIELDS[$table],它将返回[ 'email' ],因此您可以这样做:

$QUERYABLE_FIELDS['users'][0];

in_array('email', $QUERYABLE_FIELDS['users']);
相关问题