如何检查关联数组中是否存在特定项目?

how to check if particular item exists in associative array?

[
 {
 "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

您可以利用 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 {
    }
}
foreach ($array as $item){
   if($item->pid == 1) {
       //do some work...
   }
}
$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
  }

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

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