使用foreach打印对象属性

时间:2017-09-29 17:50:27

标签: php object

我有一个包含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,一切都落在后面。为什么会这样?

1 个答案:

答案 0 :(得分:1)

在您使用foreach函数时,

key()已经提升了指针,所以它提前一个。只需在foreach

中公开密钥即可
foreach($obj as $key => $data)
{
    echo "$key -> $data <br/>";
}