【发布时间】:2023-01-24 18:40:28
【问题描述】:
我有一个 PHP 脚本,它使用以下方法成功地将 JSON 字符串解码为 PHP 对象:
$amount_detail = json_decode($tuitionfee->amount_detail);
当我打印出来时,这就是我得到的
stdClass Object
(
[1] => stdClass Object
(
[amount] => 0
[date] => 2023-01-08
[amount_discount] => 55200
[amount_fine] => 0
[description] =>
[collected_by] => Super Admin(356)
[payment_mode] => Cash
[received_by] => 1
[inv_no] => 1
)
[2] => stdClass Object
(
[amount] => 36800
[date] => 2023-01-08
[description] => Collected By: Super Admin
[amount_discount] => 0
[amount_fine] => 0
[payment_mode] => Cash
[received_by] => 1
[inv_no] => 2
)
)
在尝试获取第一个对象 [amount_discount] 时,我进一步这样做:
if (is_object($amount_detail)) {
foreach ($amount_detail as $amount_detail_key => $amount_detail_value) {
$discount = $amount_detail_value->amount_discount;
}
}
但这是从第二个键 [amount_discount] 收集数据。 所以我得到的不是 55200,而是 0。
我如何也可以从第一个密钥访问数据?
【问题讨论】:
-
你是覆盖
$discount在每个循环迭代中,所以当然只有最后一个值在循环后“存活”。 -
对不起,我不明白。即使我打印这个
$amount_detail_value,我也得到了最后一个密钥。我不认为这只是关于$discount或者我错过了什么?