问题
I have an array object that looks like:
$inDatabase = Array
(
[0] => stdClass Object
(
[abc@gmail.com] => Array
(
)
)
[1] => stdClass Object
(
[xyz@gmail.com] => 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]);
}
回答1:
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
回答2:
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
回答3:
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);
来源:https://stackoverflow.com/questions/60196726/get-property-names-from-php-stdclass