Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Decoding JSON in PHP can't access the first key

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading