簡體   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"
 }
]

我有一個像上面這樣的數組。 如何檢查數組是否有特定的“pid”

例如,如果數組具有“pid”1 ,則顯示view button ,否則顯示add to cart button

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

你可以利用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"
 }
]

您可以使用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
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM