以递归方式获取对象属性和值

时间:2014-01-30 20:31:37

标签: php object foreach

所以我有一个对象:

$user->name->first = "Bob";
$user->name->last = "Smith";
$user->address->street = "1234 anywhere st.";
$user->address->city = "Chicago";
$user->address->state = "Texas";

如何在不知道“名称,地址”属性的情况下迭代此对象?

我希望能够做到

 foreach ($user as $key -> $value)
 {}

现在我可以这样做:

 foreach ($user as $key -> $value)
 {
         foreach ($value as $k => $v)
         {
           echo $k . "," . $v . "\n";
         }
 }

我得到了一个很好的小清单

 first,Bob
 last,Smith
 street,1234 anywhere st.
 city,Chicago
 state,Texas

但我怎样才能获得要打印的媒体名称或地址?

 name,first,Bob
 name,last,Smith
 address,street,1234 anywhere st.
 address,city,Chicago
 address,state,Texas

1 个答案:

答案 0 :(得分:1)

您想要的值是$key已经来自第一个foreach循环。

foreach ($user as $key => $value)
{
    foreach ($value as $k => $v)
    {
        echo "$key,$k,$v\n";
    }
}

IDEOne.com demo