1

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?

3
  • 1
    You are overwriting $discount in each loop iteration, so of course only the last value "survives" after the loop. Commented Jan 24, 2023 at 10:30
  • sorry, I don't get it. I get the last key even when i print this $amount_detail_value. I don't think it's only about $discount or what am I missing? Commented Jan 24, 2023 at 10:36
  • Where are you "printing" this? Commented Jan 24, 2023 at 10:41

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.