简体   繁体   中英

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" .

for an example if array has "pid" 1 then display view button otherwise display add to cart button

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

You can take benefit of 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.

$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
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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