从对象获取字段

时间:2016-10-20 16:01:50

标签: php mongodb symfony doctrine

我收集国家/地区的字段:name,aaa,bbb,ccc,ddd。

示例:

{_id: xxx1, name: "USA", aaa: "daf", ccc: "sdfgsdf", ddd: "234"}
{_id: xxx2, name: "Mexico", aaa: "dfg", bbb: "fdsgsdf"}
{_id: xxx3, name: "Germany", bbb: "ddfgaf"}
{_id: xxx4, name: "France"}

在我的Symfony应用程序的控制器中,我将所有对象变为$ countries和next:

foreach ($countries as $country) {
    //how can I get here fields for current object? 
    //For _id: xxx1 I would like receive "_id, name, aaa, ccc, ddd" and for _id: xxx4 I would like receive "_id, name"
}

1 个答案:

答案 0 :(得分:0)

You can use get_object_vars() and array_keys() inside your foreach.

foreach ($countries as $country) {
   $fields = array_keys(get_object_vars($country)); 
}