首页 > 解决方案 > 从 json 数组中获取数据

问题描述

这是我的 json 数组。

{"Project": [
 {
"name": "Project1",
"category": "Web",
"total_maintenance": "0",
"maintenance_start": "2021-11-01",
"maintenance_end": "2021-11-10",
"email": "test12323@test.com",
 },
{
"name": "Project1",
"category": "Mobile",
"total_maintenance": "0",
"maintenance_start": "2021-11-01",
"maintenance_end": "2021-11-10",
"email": "test12323@test.com",
},
]}

我希望能够使用像 Project[0]->name 这样的 1 个变量,但我不知道如何使用。这是在我的 laravel 函数中。

public function store(Request $request)
{
    // request()->validate([
    //     'name' => 'required',
    //     'category' => 'required',
    //     'total_maintenance' => 'required',
    //     'maintenance_start' => 'required',
    //     'maintenance_end' => 'required',
    //     'email'=> 'required',
    // ]);




    // \Log::info($request->getContent());

    $projects = $request->getContent();

    Log::info(var_dump(json_decode($request->getContent())->Project[0]->name));
}

我注释掉了,request()->validate因为如果我使用上面的 json 正文,它会不断返回错误说该字段是必需的。这只适用于我的邮递员是我使用 params 方式。无论如何我试过Log::info(var_dump(json_decode($request->getContent())->Project[0]->name));了,但我得到了

试图获取非对象错误的属性“项目”。

我也尝试过$request->all(),但也出现了另一个错误。

标签: phpjsonlaravel

解决方案


推荐阅读