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']

LDUBBS
  • 593
  • 2
  • 8
  • 20

1 Answers1

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.

Rahul
  • 18,271
  • 7
  • 41
  • 60