如何在php中循环使用json数据

如何在php中循环使用json数据,php,arrays,json,Php,Arrays,Json,我试图在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"

我试图在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']之类的东西时,我总是会得到一个非法的偏移量错误。

如文档中所述:

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

若你们并没有将第二个参数传递为true,那个么它将被视为object,如下所示

$arr = json_decode($arr);
$names = [];
foreach ($arr->cart as $item) {
    $names[] = $item->name;
}
echo $arr->total;// this is how you will get total.
$names  = [];
$arr = json_decode($arr, true);
foreach ($arr['cart'] as $item) {
    $names[] = $item['name'];
}
echo $arr['total'];// this is how you will get total.
如果将第二个参数传递为true,则它将被视为关联数组,如下所示

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

在代码中,数据有两个主键,即<代码>购物车和
总计
。您正试图从中获取我在回答中指定的
cart
的数据。

它是数组中的一个数组。您没有对此进行说明。这是可行的,但它只返回第一个数组中的数据,我无法访问“total”。您应该指出,所需的数据位于
购物车
数组中,而不是解码数组的根。你的答案是正确的,但只是缺少一个完整的解释。对,约翰,我需要能够获得“购物车”数据和总数。我在我的答案中做了更改。请看一看,这是一种享受。谢谢拉胡尔。