无法在 laravel 控制器中获取 json 数据

Not able to fetch the json data in laravel controller

我想从 children 字段获取数据或获取 children 的数量。

我是这样取的: $temp = json_decode($request->get('tempData');

这是我的 json 负载:

tempData:[{
      "id":"c625",
      "name":"Chapter 1",
      "children":[
         {
            "id":3,
            "type":"study material",
            "content":"Demo Study Material Title 2"
         },
         {
            "id":4,
            "type":"study material",
            "content":"Demo Study Material Title 3"
         },
         {
            "id":5,
            "type":"study material",
            "content":"Demo Study Material Title 4"
         }
      ],
      "type":"chapter"
   }
]

您可以创建一个新数组并使用 foreach 循环将子数组推送到该数组中。

$temp = json_decode($request->get('tempData');
$children = array();
$child_count = 0;
foreach ($temp['children'] as $child) {
    $child_count++;
    array_push($children, $child);
}

您可以使用 collection

获取 tempData 数组中所有项目的 children 计数
collect(json_decode($request->get('tempData'), true))
->mapWithKeys(fn($item) => [$item['id'] => count($item['children'])])
->all();

获取每个 id 的 children 计数结果:

 [
    "c625" => 3
 ]