[英]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.