【问题标题】:Decoding JSON in PHP can't access the first key在 PHP 中解码 JSON 无法访问第一个密钥
【发布时间】: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 或者我错过了什么?

标签: php json


【解决方案1】:

每次执行循环时,$discount 变量都会被覆盖。所以你总是会得到最后的数据。

所以如果你只想要第一个索引值然后使用current()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 2019-04-21
    相关资源
    最近更新 更多