Home > Mobile >  Decoding JSON in PHP can't access the first key
Decoding JSON in PHP can't access the first key

Time:01-25

I have a PHP script which successfully decodes a JSON string into a PHP object using:

 $amount_detail = json_decode($tuitionfee->amount_detail);

when I print it out, this is what I get

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
        )

)

In trying to get the first object [amount_discount], I went further to do this:

if (is_object($amount_detail)) {
     foreach ($amount_detail as $amount_detail_key => $amount_detail_value) {
             $discount = $amount_detail_value->amount_discount;                                       
                                            }
} 

But this is collecting data from the second key [amount_discount]. So instead of getting 55200, I'm getting 0.

How do I get to access data from the first key too?

CodePudding user response:

The $discount variable gets over-written each time loop is executed. So you will always get the last data.

So if you want only the first index value then use current()

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

Output: https://3v4l.org/8Wvqv

Note: In case you want all discount output then in your loop echo the $discount variable.

  • Related