嗨,我遇到了使用foreach循环数组的问题。我有这个数组:
stdClass Object
(
[GetAllCitiesResult] => stdClass Object
(
[status] => Success
[returnValue] => SoapVar Object
(
[enc_type] => 0
[enc_value] => stdClass Object
(
[City] => Array
(
[0] => stdClass Object
(
[id] => 7326
[name] => Paris
[postCode] => 7700
)
[1] => stdClass Object
(
[id] => 262
[name] => Berlin
[postCode] => 2932
)
)
)
[enc_stype] => ArrayOfCity
[enc_ns] => http://example.com/services/v1.1
)
)
)
我尝试使用这个PHP代码循环:
echo "<select>";
foreach($result as $citys) {
echo "<option>" . $citys . "</option>";
}
echo "</select>";
当我尝试这段代码时,它会向我显示此错误“可捕获的致命错误:类别stdClass的对象无法在第X行的C:\ xampp \ htdocs \ test \ index.php中转换为字符串”
我想在每次运行代码时检查对象“status”,我希望数组“City”中的对象名称进入下拉列表。
答案 0 :(得分:2)
这种情况正在发生,因为您试图打印$ city,这不是一个字符串,它是一个stdClass。
您需要浏览数组,直到将City作为初始数组,然后才能执行
foreach($city as $cityRecord){
print '<option>' . $cityRecord['name'] . '</option'>
}
希望能帮助