0
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;
    }
    ?>

I'd need to retrieve the array key where its located for comment_parent 30 which is in [2] array. I've tried with array_search but i'm getting this error:

Warning: array_search() expects parameter 2 to be array, object given in

Thanks.

Kheshav Sewnundun
  • 1,236
  • 15
  • 37
Marx
  • 71
  • 2
  • 13

2 Answers2

2

Try this..Your array has object so you have to fetch value by object, and use the logic below to get key..

foreach ($array as $key=>$obj){
    if($obj->comment_parent == 30){
        break;      
    }
}
echo "Required Key is ==>".$key;
Prashant M Bhavsar
  • 1,136
  • 9
  • 13
0

Maybe you should cast the object as follows

$key = array_search ("30", (array)$comments);

This will fix your error but won't do the work you need. Better check the answer of @Prashant M Bhavsar

$commentKey = null;
foreach ($array as $key=>$obj)
{
    if(isset($obj->comment_parent) && $obj->comment_parent == 30){
        $commentKey = $key;
        break;
    }
}

For more complicated structures or statements you can use array_map function.

Lachezar Todorov
  • 903
  • 9
  • 21