简体   繁体   English

使用键在数组中搜索特定值

[英]Search for specific value in array with keys

I have an array that is filled with values dynamically and I have to check if a value exists. 我有一个动态填充值的数组,我必须检查值是否存在。

I tried the follwing but it's not working: 我尝试了以下操作,但无法正常工作:

while (.....) {
    $fileData[] = array( "sku" => $sku, "qty" => $qty);
}

$product_sku = $product->getSku();

if (in_array(array("sku",$product_sku), $fileData)){
    echo "OK <BR/>";    
}
else{
    echo "NOT FOUND <BR/>"; 
}

The whole thing with keys confuses me. 整个带钥匙的事情使我感到困惑。 Should I change the table structure or just the in_array() statement? 我应该更改表结构还是仅更改in_array()语句? Can you help me find a solution? 您能帮我找到解决方案吗?

You can see if a key exists in an array with: 您可以使用以下命令查看数组中是否存在键:

array_key_exists('sku', $fileData);

also, you can just check it directly: 另外,您可以直接检查它:

if (isset($fileData['sku'])

It looks like you might be trying to recursively check for a key though? 看来您可能正在尝试递归检查密钥? I think we'd need to see what getSku() returns. 我认为我们需要查看getSku()返回的内容。 $fileData[] appends a value to an existing array so if $fileData was an empty array you'd have $ fileData []将一个值附加到现有数组,因此如果$ fileData是一个空数组

fileData[0] = array("sku" => $sku, "qty" => $qty);

not

fileData = array("sku" => $sku, "qty" => $qty);

Try this on for size (with some fake data for demo purposes): 试一下以获取大小(为演示目的提供一些虚假数据):

$fileData = array(
    array("sku" => "sku1", "qty" => 1),
    array("sku" => "sku2", "qty" => 2),
);

$sku = "sku2"; // here's the sku we want to find
$skuExists = false;

// loop through file datas
foreach ($fileData as $data)
{
    // data is set to each array in fileData
    // check if sku exists in that array
    if (in_array($sku, $data))
    {
        // if it does, exit the loop and flag
        $skuExists = true;
        break;
    }
}

if ($skuExists)
{
    // do something
}

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

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