简体   繁体   English

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

[英]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"
 }
]

I have an array like above.我有一个像上面这样的数组。 how to check if array has particular "pid" .如何检查数组是否有特定的“pid”

for an example if array has "pid" 1 then display view button otherwise display add to cart button例如,如果数组具有“pid”1 ,则显示view button ,否则显示add to cart button

foreach ($array as $item){
   if($item->pid == 1) {
       //do some work...
   }
}

You can take benefit of isset() & !empty()你可以利用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 {
    }
}
$array = [
 {
 "pid": "1",
 "pname": "Burger",
 "price": "20",
 "qnty": "1",
 "pimg": "1.jpg"
 },
 {
 "pid": "2",
 "pname": "Cheese burger",
 "price": "30",
 "qnty": "1",
 "pimg": "2.jpg"
 }
]

You can use isset fucntion.您可以使用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
  }

You need to iterate array using loop and then check the value against any index of array您需要使用循环迭代数组,然后根据数组的任何索引检查该值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM