如何检查数组键是否等于数组的值,如下所示:
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";
}发布于 2012-01-05 12:16:47
这是行不通的,因为你有一个标准对象数组……唯一存在的数组键是整数。所以问题是你想要检测什么?如果你想检查一个对象是否有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
}我不认为这是你真正想要做的,但一些更多的信息会有所帮助。
发布于 2012-01-05 12:22:19
看起来您正在使用fetch_object()。这将为您提供对象数组。如果您想要处理数组,请使用fetch_assoc()来使用array_key_exists,您需要循环结果,因为它是多维数组。
https://stackoverflow.com/questions/8737546
复制相似问题