所以我有一个对象:
$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
答案 0 :(得分:1)
您想要的值是$key
已经来自第一个foreach
循环。
foreach ($user as $key => $value)
{
foreach ($value as $k => $v)
{
echo "$key,$k,$v\n";
}
}