Get property names from PHP stdClass

自古美人都是妖i 提交于 2020-02-29 05:36:17

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!