如何在 PHP 中获取可捕获致命错误的 foreach 数组
How to foreach array whitout get Catchable fatal error in PHP
您好,我在使用 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>";
当我尝试此代码时,它显示此错误 "Catchable fatal error: Object of class stdClass could not be converted to string in C:\xampp\htdocs\test\index.php on line X"
我想在每次 运行 代码时检查对象 "status",我希望数组 "City" 中的对象名称进入下拉列表。
发生这种情况是因为您正在尝试打印 $cities,它不是字符串,而是 stdClass。
您需要在数组中导航,直到您将 City 作为初始数组,然后您可以
foreach($city as $cityRecord){
print '<option>' . $cityRecord['name'] . '</option'>
}
希望这会有所帮助
您好,我在使用 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>";
当我尝试此代码时,它显示此错误 "Catchable fatal error: Object of class stdClass could not be converted to string in C:\xampp\htdocs\test\index.php on line X"
我想在每次 运行 代码时检查对象 "status",我希望数组 "City" 中的对象名称进入下拉列表。
发生这种情况是因为您正在尝试打印 $cities,它不是字符串,而是 stdClass。
您需要在数组中导航,直到您将 City 作为初始数组,然后您可以
foreach($city as $cityRecord){
print '<option>' . $cityRecord['name'] . '</option'>
}
希望这会有所帮助