Marx
Marx

Reputation: 71

Get the first level key from a 2d array where a column value is found

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

Upvotes: 0

Views: 1264

Answers (2)

Prashant M Bhavsar
Prashant M Bhavsar

Reputation: 1164

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;

Upvotes: 2

Lachezar Todorov
Lachezar Todorov

Reputation: 923

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.

Upvotes: 0

Related Questions