简体   繁体   English

如何检查关联数组中是否存在值

[英]How to check whether a value exists in an associative array

I have an array that is the result of a SELECT query and would like to check whether a certain value exists in that array.我有一个数组,它是 SELECT 查询的结果,并且想检查该数组中是否存在某个值。
I tried the following but this does not find the value and always returns that the value does not exist in the array.我尝试了以下方法,但这没有找到该值,并且始终返回该值在数组中不存在。

I am assuming I am referring wrongly to the array.我假设我错误地引用了数组。 Can someone show me how to do this right?有人可以告诉我如何正确地做到这一点吗?

My array:我的数组:

array ( 0 => array ( 'itemName' => 'bandwidth', 'itemType' => 'number', 'itemUnit' => 'mbit', ), 1 => array ( 'itemName' => 'bSize', 'itemType' => 'number', 'itemUnit' => 'sqm', ), 2 => array ( 'itemName' => 'bArea', 'itemType' => 'number', 'itemUnit' => 'sqm', ), )

My PHP:我的 PHP:

// ...
$resultC = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
var_export($resultC);
if(in_array('bandwidth', $resultC)) {
    echo 'exists in array';
} else {
    echo 'does not exist in array';
}

You may use the combination of array_column with in_array for your case.您可以针对您的情况使用array_columnin_array的组合。

$resultC = [
    0 => ['itemName' => 'bandwidth', 'itemType' => 'number', 'itemUnit' => 'mbit'],
    1 => ['itemName' => 'bSize', 'itemType' => 'number', 'itemUnit' => 'sqm'],
    2 => ['itemName' => 'bArea', 'itemType' => 'number', 'itemUnit' => 'sqm'],
];

return in_array('bandwidth', array_column($resultC, 'itemName'));

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

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