Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get an object "key" from the value? Is there something like array_search for objects?

I have a class like so:

stdClass Object
(
    [id] => 1
    [items] => stdClass Object
        (
            [0] => 123
            [1] => 234
            [2] => 345
            [3] => 456
        )
    )
)

Let's call the above object $foo.

Let's say $v = 234. Given $foo and $v, how can I return the "key" 1?

If $foo->items was an array I would simply do $key = array_search($v,$foo->items);. But this doesn't work in an object.

How can I find the key for $v without looping through the object in some foreach?

like image 999
Ryan Avatar asked Feb 20 '23 02:02

Ryan


1 Answers

Use get_object_vars and search through the array returned.

Reference: http://php.net/manual/en/function.get-object-vars.php

Here's an example of how to search through the array returned for a key:

<?php
$foo = NULL;
$foo->id = 1;
$foo->items = array(123, 234, 345, 456);
$foo_array = get_object_vars($foo);
print_r($foo_array);

foreach ($foo_array as $key => $value) {
    if ($value == 1) {
        echo $key;
    }
}
?>

Output:

Array
(
    [id] => 1
    [items] => Array
        (
            [0] => 123
            [1] => 234
            [2] => 345
            [3] => 456
        )

)
id

CodePad: http://codepad.org/in4w94nG

like image 180
Daniel Li Avatar answered Apr 06 '23 23:04

Daniel Li