0

I'm trying to loop through JSON data in php.

array:2 [
  "cart" => array:3 [
    0 => array:4 [
      "id" => 3
      "name" => "ying"
      "price" => "4000"
    ]
    1 => array:4 [
      "id" => 2
      "name" => "yang"
      "price" => "4000"
    ]
    2 => array:4 [
      "id" => 4
      "name" => "foo"
      "price" => "5000"
    ]
  ]
  "total" => 13000
]

I've used the json_decode function and a foreach over the data.

foreach (json_decode($arr) as $item) {
    $item['name'];
}

I want to be able to get each "cart" item and the single "total" data but I keep getting an illegal offset error when i try to call things like $item['name']

1
  • 3
    It's an array within an array. You are not accounting for that. Commented Sep 10, 2019 at 11:56

1 Answer 1

0

As written in json_decode doc:

Note: When TRUE, returned objects will be converted into associative arrays.

If you dont pass 2nd argument as true then it will be treated as object as below.

$arr = json_decode($arr);
$names = [];
foreach ($arr->cart as $item) {
    $names[] = $item->name;
}
echo $arr->total;// this is how you will get total.

If you pass 2nd argument as true then it will be treated as associative array as below.

$names  = [];
$arr = json_decode($arr, true);
foreach ($arr['cart'] as $item) {
    $names[] = $item['name'];
}
echo $arr['total'];// this is how you will get total.

In your code, your data is having two main keys viz. cart and total. From which, you are trying to fetch the data of cart which I specified in my answer.

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

6 Comments

This works but it returns data from the first array only and i can't access 'total'
You should point out that the data need is in the cart array and not the root of the decoded array. Your answer is correct but just lacks a complete explanation.
Right John, i need to be able to get 'cart' data and total.
I made changes in my answer. Please have a look.
Thanks Rahul but i'm trying to fetch data for 'cart' and 'total'
|

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.