【问题标题】:check and compare associative array value with in_array?检查关联数组值并将其与 in_array 进行比较?
【发布时间】:2020-01-22 15:57:42
【问题描述】:

我正在尝试使用in_array 函数来检查第二个数组中是否存在该值。我想从以下数组中搜索 556729685:

$_SESSION["cart_item"] =

Array
( 
    [cart_item] => Array 
        ( 
            [0] => Array 
                ( 
                    [product_name] => White Sakura Necktie
                    [id] => 11
                    [product_auto_id] => 556729685
                    [quantity] => 2
                    [product_regular_price] => 95
                    [product_sale_price] => 95
                    [product_image] => 556729680Black_Sakura_Necktie.jpg 
                )
            [1] => Array 
                ( 
                    [product_name] => hhhad ba bhdbh
                    [id] => 10
                    [product_auto_id] => 951790801
                    [quantity] => 2
                    [product_regular_price] => 20
                    [product_sale_price] => 
                    [product_image] => 951790801hhhad_ba_bhdbh_.jpg 
                )
        ) 
)

我正在使用以下功能进行检查,但输出错误:

in_array(556729685, array_keys($_SESSION["cart_item"]));

我也试过这个:

in_array(556729685, array_values($_SESSION["cart_item"]));

没有工作,所以请帮我解决这个问题。

【问题讨论】:

    标签: arrays session associative-array


    【解决方案1】:

    关联数组由键、列和值组成。因此,为了检查值的存在,您需要到达数组的键。

    for($i=0;$i<count($_SESSION["cart_item"]);$i++)
    {
         if( in_array( 556729685 ,$_SESSION["cart_item"][$i] ) )
        {
          echo "exist in id:".$i.'<br/>';
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-08
      • 1970-01-01
      • 2012-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多