我有一个包含10个属性的匿名对象,我需要按以下格式打印它们:{name} - > {value)
这是我的代码:
$obj = new stdClass();
$obj->name = "Penka";
$obj->age = "25";
$obj->city = "Sofia";
$obj->street = "Hadji Dimitar street";
$obj->occupation = "PHP developer";
$obj->children = 1;
$obj->married = false;
$obj->divorced = true;
$obj->salary = 1300;
$obj->car = "Nissan Micra";
foreach($obj as $data)
{
echo key($obj).' -> '.$data.'<br/>';
}
我不知道如何输出密钥但我发现这个函数key()
并且它有点工作但输出失真了。
age -> Penka
city -> 25
street -> Sofia
occupation -> Hadji Dimitar street
children -> PHP developer
married -> 1
divorced ->
salary -> 1
car -> 1300
-> Nissan Micra
缺少属性name
,一切都落在后面。为什么会这样?
答案 0 :(得分:1)
foreach
函数时, key()
已经提升了指针,所以它提前一个。只需在foreach
:
foreach($obj as $key => $data)
{
echo "$key -> $data <br/>";
}