簡體   English   中英

如何檢查關聯數組中是否存在值

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

我有一個數組,它是 SELECT 查詢的結果,並且想檢查該數組中是否存在某個值。
我嘗試了以下方法,但這沒有找到該值,並且始終返回該值在數組中不存在。

我假設我錯誤地引用了數組。 有人可以告訴我如何正確地做到這一點嗎?

我的數組:

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', ), )

我的 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';
}

您可以針對您的情況使用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