如何循环遍历JSON数据php [英] How to loop through json data php

查看:62
本文介绍了如何循环遍历JSON数据php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历php中的JSON数据.

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
]

我使用了json_decode函数和对数据的foreach.

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

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

我希望能够获取每个购物车"商品和单个总计"数据,但是当我尝试调用$ 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']

推荐答案

注意::为TRUE时,返回的对象将转换为关联数组.

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

如果您不将第二个参数传递为true,则将其视为对象,如下所示.

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.

如果将第二个参数传递为true,则它将被视为关联数组,如下所示.

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.

这篇关于如何循环遍历JSON数据php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆