【问题标题】:How to loop through json data php如何循环通过json数据php
【发布时间】:2020-01-12 04:20:36
【问题描述】:

我正在尝试在 php 中循环遍历 JSON 数据。

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。

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

我希望能够获取每个“购物车”项目和单个“总”数据,但是当我尝试调用诸如 $item['name'] 之类的东西时,我不断收到非法偏移错误

【问题讨论】:

  • 数组中的数组。你没有考虑到这一点。

标签: php arrays json


【解决方案1】:

json_decode doc 中所写:

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

如果您没有将第二个参数作为 true 传递,那么它将被视为对象,如下所示。

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

如果您将第二个参数作为 true 传递,那么它将被视为关联数组,如下所示。

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

在您的代码中,您的数据有两个主键,即。 carttotal。您正在尝试从中获取我在答案中指定的cart 的数据。

【讨论】:

  • 这可行,但它只从第一个数组返回数据,我无法访问'total'
  • 您应该指出需要的数据在cart 数组中,而不是解码数组的根。您的答案是正确的,但缺少完整的解释。
  • 对,约翰,我需要能够获取“购物车”数据和总数。
  • 我对答案进行了更改。请看一看。
  • 工作愉快。谢谢拉胡尔。
猜你喜欢
  • 2015-03-25
  • 2017-09-18
  • 1970-01-01
  • 2015-10-12
  • 2019-05-27
  • 1970-01-01
  • 2013-08-19
  • 2017-03-13
  • 2016-04-26
相关资源
最近更新 更多