-1

我有一个类似的数组:

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 但没有得到任何结果。

是否有任何内置函数可以在不将数组置于循环中的情况下对其进行检查。

4

2 回答 2

0

您可以遍历每个产品:

foreach($array as $product) {
    if(isset($product['product_id']))
        // do something
}

我认为没有内置函数可以处理这个问题。

于 2013-11-03T12:46:29.207 回答
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);
?>
于 2013-11-03T13:02:56.137 回答