在PHP中解码JSON无法访问第一个键

pbwdgjma  于 2023-01-24  发布在  PHP
关注(0)|答案(1)|浏览(114)

我有一个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。
我如何也从第一个键访问数据?

eyh26e7m

eyh26e7m1#

$discount变量在每次循环执行时都会被覆盖,所以你总是会得到最后的数据。
因此,如果只需要第一个索引值,则使用current()

$discount = current((Array)$amount_detail_value)->amount_discount;

输出:https://3v4l.org/8Wvqv
注意:如果你想要所有的折扣输出,然后在你的循环echo$discount变量.

相关问题