检查数组中是否存在值

时间:2016-06-01 11:44:23

标签: php arrays

我想检查产品是否存在于wishlist数组中,因此我可以创建一个函数来获取wishlist中的产品ID,结果是

Array
    (
    [0] => Array
        (
            [product_id] => 28
        )

    [1] => Array
        (
            [product_id] => 30
        )

    [2] => Array
        (
            [product_id] => 42
        )
    )

我的代码是

foreach ($products as $product)
 show products in this style else in this style

我想检查一下

$product['product_id'] = the product id in $wishids array

3 个答案:

答案 0 :(得分:4)

您可以将in_arrayarray_column一起使用,请参阅以下示例:

if(in_array($productID, array_column($wishids, 'product_id'))
  echo 'Match found';
else 
  echo 'Match not found';

答案 1 :(得分:1)

Ofcourse。你可以使用php的in_array()函数来完成它。 你可以在这里参考。

http://www.w3schools.com/php/func_array_in_array.asp

所有你需要做的就是在遍历$ products的循环中调用此函数并将id传递给函数。你会得到相应的结果。

答案 2 :(得分:0)

使用in_array

foreach ($products as $product)
{
if(in_array(product['product_id'] , $wishids)
{ 
  //do something
}
相关问题