1
$json='{ 
        "status": true, 
        "data": { 
                "code": "44882S", 
                "quantity": 124740, 
                "amount": 124740, 
                "date": "2020-01-15"
                } 
    }';

and I've made the code and the code doesn't work

$get = json_decode($json, true);
foreach ($get->data as $key) {
     $code = $key->code;
    $quantity = $key->quantity;
    $amount = $key->amount;
    $date = $key->date;
}

Is there something wrong with my code?

2
  • just dd($get) and see if get the data. Commented Jan 15, 2020 at 14:02
  • dd() is from laravel and I'm not sure if he is using it. Use print_r() instead. Commented Jan 15, 2020 at 14:11

1 Answer 1

3

You requested json_decode to make the objects into arrays!

So either dont ask for the objects to be converted to an array

Also if you are looping over the object/array, you will get One entery per iteration and not all 4 at once.

$get = json_decode($json);
foreach ($get->data as $key=>$val) {
    echo "$key = $val";
}

OR treat each value as an array value

$get = json_decode($json, true);
foreach ($get['data'] as $key=>$val) {
    echo "$key = $val";
}
Sign up to request clarification or add additional context in comments.

5 Comments

We are looping over data already, so inside the loop, there will not be a $key->code, but $keywill be the value of code (and quantity, amount and date in the next three iterations) already.
@04FS Good point, I knew something was niggling in the back of my head
@RiggsFolly sorry, mate :-), but that edit still makes rather little sense. Now all four variables inside the loop get overwritten each time, so in the end they will all four of them contain 2020-01-15. This doesn’t actually need a loop, OP’s attempt was a bit misleading to begin with.
That's true @04FS, otherwise this is just remapping.
@04FS Ha PENNY DROPPED, and code changed accordingly. Must be having a DUMB Half Hour :) Thanks for the sanity check :) :)

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.