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? Can you help me find a solutio开发者_开发问答n?
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. $fileData[] appends a value to an existing array so if $fileData was an empty array you'd have
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
}
精彩评论