我有一个类似的数组:
Array
(
[0] => Array
(
[product_id] => 1
[product_name] => T-Shirts
[quantity] => 2
[price] => 300
)
[1] => Array
(
[product_id] => 2
[product_name] => Red Shirt
[quantity] => 4
[price] => 200
)
[2] => Array
(
[product_id] => 3
[product_name] => Cap
[quantity] => 2
[price] => 50
)
)
我想检查product_id是否存在。我试图in_array但没有得到任何结果。
是否有任何内置函数可以在不将数组放入循环的情况下进行检查。
答案 0 :(得分:0)
您可以遍历每个产品:
foreach($array as $product) {
if(isset($product['product_id']))
// do something
}
我认为没有内置函数来处理这个问题。
答案 1 :(得分:0)
正如gloomy.penguin所提到的,你可以使用array_filter
<?php
$a = Array
(
0 => Array
(
"product_id" => 1,
"product_name" => "T-Shirts",
"quantity" => 2,
"price" => 300,
),
1 => Array
(
"product_id" => 2,
"product_name" => "Red Shirt",
"quantity" => 4,
"price" => 200,
),
2 => Array
(
"product_id" => 3,
"product_name" => "Cap",
"quantity" => 2,
"price" => 50,
),
);
$result = array_filter($a, function($var) {
if ($var['product_id'] == 3) return true;
});
if (empty($result)) echo "Not found";
else echo "Found";
echo var_dump($result);
?>