【问题标题】:how to check if particular item exists in associative array?如何检查关联数组中是否存在特定项目?
【发布时间】:2020-10-01 21:29:29
【问题描述】:
[
 {
 "pid": "1",
 "pname": "Burger",
 "price": "20",
 "qnty": "1",
 "pimg": "1.jpg"
 },
 {
 "pid": "2",
 "pname": "Cheese burger",
 "price": "30",
 "qnty": "1",
 "pimg": "2.jpg"
 }
]

我有一个像上面这样的数组。如何检查数组是否有特定的 "pid"

例如,如果数组有 "pid" 1,则显示view button,否则显示add to cart button

【问题讨论】:

标签: php arrays laravel associative-array


【解决方案1】:

您可以利用 isset()!empty()

foreach($lists as $list) {
    if(isset($list['pid']) && (!empty($list['pid']))) { // this will check if a key exists. If yes, then check for it's value. If value is there, then true
        // pid exists and has a value
    } else {
    }
}

【讨论】:

    【解决方案2】:
    foreach ($array as $item){
       if($item->pid == 1) {
           //do some work...
       }
    }
    

    【讨论】:

      【解决方案3】:
      $array = [
       {
       "pid": "1",
       "pname": "Burger",
       "price": "20",
       "qnty": "1",
       "pimg": "1.jpg"
       },
       {
       "pid": "2",
       "pname": "Cheese burger",
       "price": "30",
       "qnty": "1",
       "pimg": "2.jpg"
       }
      ]
      

      你可以使用isset函数。

      $key = 1;
      $count =0 ;
      
      foreach($array as $a) {
          if(isset(array_search($key,$a))){
             //your logic to execute if the $key is there in the array
             $count ++;
         }
       }
        if($count==0){
            //add to cart logic
        }
      

      【讨论】:

      • 您的第二部分代码无效,完全错误。
      • 您无法通过empty() 验证密钥。请参阅php.net/manual/en/function.empty.php
      • 因为我们在数组中没有赋值运算符。
      • 我想检查数组是否有特定的“pid”,如果是,则显示“查看按钮”,因为 pid 已经在数组中,如果数组中不存在,则显示“添加到购物车按钮”但在这里如果 pid 不存在,则“添加到购物车按钮”显示与数组中可用的键一样多。如果 pid 存在,那么它会显示视图按钮,这是好的
      • @Maulik 我在这里所做的是分配要在分配给pid 的数组中找到的值,并循环遍历数组以查找该值是否分配给循环使用array_search
      【解决方案4】:

      您需要使用循环迭代数组,然后根据数组的任何索引检查值

      foreach ($items as $item){
         if($item->pid == 1) {
             // do whatever you want to do
         }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-05
        • 2012-08-02
        • 2015-10-09
        • 2020-04-11
        • 1970-01-01
        • 2021-08-24
        • 2017-12-29
        • 1970-01-01
        相关资源
        最近更新 更多