[英]PHP How to check if an array key equals a certain value?
我如何检查数组键等于这样的数组的值:
Array ( [0] => stdClass Object ( [subCategory] => All Headphones [description] => [image] => ) [1] => stdClass Object ( [subCategory] => Behind-the-Neck Headphones [description] => [image] => ) [2] => stdClass Object ( [subCategory] => Clip-On Headphones [description] => [image] => ) [3] => stdClass Object ( [subCategory] => Earbud Headphones [description] => [image] => ) [4] => stdClass Object ( [subCategory] => Kids' Headphones [description] => [image] => ) )
我尝试使用此代码:
if(array_key_exists('subCategory',$array) {
echo "Exists";
}
那将行不通,因为您有一个标准对象数组...甚至出现的唯一数组键是整数。 所以问题是您要检测什么? 如果要检查对象是否具有subCategory
属性,可以执行isset($obj->subCategory)
。 如果要确保数组中的每个对象都具有该属性,则需要循环:
function hasSubCategory($array){
foreach($array as $element) {
if(!isset($element->subCategory)){
return false; // if any object doesnt have the property
}
}
return true; // if all objects have the property
}
我认为那不是您真正想要做的,更多信息可能会有所帮助。
似乎您正在使用fetch_object()。 这为您提供了对象数组。 如果要使用数组,请使用fetch_assoc()要使用array_key_exists,则需要循环处理结果,因为它是多维数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.