DCR
DCR

Reputation: 15700

Get property names from PHP stdClass

I have an array object that looks like:

$inDatabase = Array
(
    [0] => stdClass Object
        (
            [[email protected]] => Array
                (
                )
        )
    [1] => stdClass Object
        (
            [[email protected]] => Array
                (
                )
        )
)

How do I push email addresses onto a new array? I tried the following:

$innerKeys =[];
$temp=[];
for($i=0;$i<2;$i++){
   $temp = array_keys($inDatabase[$i])

   //so I thought $temp[0] would have the email address but $temp is null.

   array_push($innerKeys,$temp[0]);

}

Upvotes: 1

Views: 3156

Answers (3)

AbraCadaver
AbraCadaver

Reputation: 78994

You can also just cast to an array and get the first key. I modified it a bit:

foreach($inDatabase as $o) {
   $innerKeys[] = array_keys((array)$o)[0];
}

However, since you want the first one, key (surprisingly) will work on an object:

foreach($inDatabase as $o) {
   $innerKeys[] = key($o);
}

Or much simpler:

$innerKeys = array_map('key', $inDatabase);

Upvotes: 1

Barmar
Barmar

Reputation: 781868

array_keys() is for arrays. To turn the object properties into an array, use get_object_vars(). So you want

$temp = array_keys(get_object_vars($inDatabase[$i]));

DEMO

Upvotes: 3

fubar
fubar

Reputation: 17398

You can use array_reduce(), get_object_vars(), and array_keys().

$emails = array_reduce($inDatabase, function ($arr, $obj) {
    return array_merge($arr, array_keys(get_object_vars($obj)));
}, []);

Working example: https://3v4l.org/IU3C9

Upvotes: 1

Related Questions