简体   繁体   English

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

[英]Check if associative array contains key-value pair

Suppose I have an array whose elements are like this: 假设我有一个数组,其元素如下所示:

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

How can I check if "Canada" => "Ottawa" is present in this array? 如何检查此数组中是否存在"Canada" => "Ottawa"

Looking down the list of Array Functions in the docs, I don't see anything built-in to do this. 在文档中的“ 数组函数 ”列表中查找,我看不到任何内置函数可以做到这一点。 But it's easy to roll your own utility function for it: 但是,为它滚动自己的实用程序功能很容易:

/*
    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;
}

Example usage: 用法示例:

$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
if (isset($elements[$country]) AND $elements[$country] == $capitale) {
    return true;
}
return false;

I put a couple of these answers together and arrived at this: 我将以下几个答案放在一起,得出了以下结论:

// 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);

To break it down further, if you have an associative array that has some complex values in it, you can use array_key_exists() to check for them by name. 为了进一步分解,如果您的关联数组中包含一些复杂的值,则可以使用array_key_exists()按名称检查它们。

If the key exists, you can read its value as normal, as shown in my example above, as $QUERYABLE_FIELDS[$table] which will return [ 'email' ] , so you could do: 如果键存在,您可以正常读取其值,如上面的示例所示,为$QUERYABLE_FIELDS[$table] ,它将返回[ 'email' ] ,因此您可以执行以下操作:

$QUERYABLE_FIELDS['users'][0];

or 要么

in_array('email', $QUERYABLE_FIELDS['users']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM