Array
(
[0] => stdClass Object
(
[comment_ID] => 31
[comment_post_ID] => 16
[comment_karma] => 0
[comment_approved] => 1
[comment_parent] => 0
)
[1] => stdClass Object
(
[comment_ID] => 32
[comment_post_ID] => 16
[comment_karma] => 0
[comment_approved] => 1
[comment_parent] => 31
)
[2] => stdClass Object
(
[comment_ID] => 33
[comment_post_ID] => 16
[comment_karma] => 0
[comment_approved] => 1
[comment_parent] => 30
)
)
<?
foreach ($array as $comments)
{
$key = array_search ("30", $comments);
echo $key;
}
?>
我需要检索数组键,它位于[2]数组中的comment_parent 30。我尝试过使用array_search但是我收到了这个错误:
警告:array_search()期望参数2是数组,给定对象 在
感谢。
答案 0 :(得分:2)
试试这个..你的数组有对象,所以你必须按对象获取值,并使用下面的逻辑来获取密钥..
foreach ($array as $key=>$obj){
if($obj->comment_parent == 30){
break;
}
}
echo "Required Key is ==>".$key;
答案 1 :(得分:0)
也许您应该按如下方式投射对象
$key = array_search ("30", (array)$comments);
这将解决您的错误,但不会完成您需要的工作。 更好地检查@Prashant M Bhavsar的答案
$commentKey = null;
foreach ($array as $key=>$obj)
{
if(isset($obj->comment_parent) && $obj->comment_parent == 30){
$commentKey = $key;
break;
}
}
对于更复杂的结构或语句,您可以使用array_map函数。