如何更新嵌套 Laravel collection 中的嵌套值
How to update a nested value within a nested Laravel collection
我有一个 deployments
Laravel Collection 这样的:
Illuminate\Support\Collection {#415 ▼
#items: array:5 [▼
0 => array:7 [▼
"id" => 31
"status" => "active"
"name" => "Deployment 1"
"spots" => array:4 [▼
0 => array:2 [▼
"id" => 33
"status" => "active" <-- Want to change this
]
1 => array:2 [▶]
2 => array:2 [▶]
3 => array:2 [▶]
]
"data" => array:3 [▶]
]
1 => array:7 [▶]
2 => array:7 [▶]
3 => array:7 [▶]
4 => array:7 [▶]
]
}
我想将嵌套的 status
值更新为 inactive
。我使用了 Laravel map
函数,但它似乎只适用于具有一层嵌套的 collections 。所以这个...
$this->deployments->map(function ($deployment) {
$deployment['spots'][0]['status'] = 'inactive';
});
dd($this->deployments);
...保持 $this->deployments
不变。
还尝试使用嵌套 map
函数在第二层获得 Call to a member function map() on array
异常,因为第二层和下一个嵌套层被视为数组...
有什么想法吗?
提前致谢。
使用 map
方法,您就快成功了。您将必须 return 在 $deployment
中所做的更改,并在最后执行 ->all()
以使用修改后的值更新集合。
更新单点:
$deployments = $deployments->map(function($deployment){
$deployment['spots'][0]['status'] = 'inactive';
return $deployment;
})->all();
更新所有景点:
$deployments = $deployments->map(function($deployment){
foreach($deployment['spots'] as &$spot){
$spot['status'] = 'inactive';
}
return $deployment;
})->all();
对于任何研究这个的人来说,一个更优雅的解决方案可能是:
更新单点:
$data = $deployments->all();
$deployments = data_set($data, 'spots.0.status', 'inactive');
更新所有景点:
$data = $deployments->all();
$deployments = data_set($data, 'spots.*.status', 'inactive');
我有一个 deployments
Laravel Collection 这样的:
Illuminate\Support\Collection {#415 ▼
#items: array:5 [▼
0 => array:7 [▼
"id" => 31
"status" => "active"
"name" => "Deployment 1"
"spots" => array:4 [▼
0 => array:2 [▼
"id" => 33
"status" => "active" <-- Want to change this
]
1 => array:2 [▶]
2 => array:2 [▶]
3 => array:2 [▶]
]
"data" => array:3 [▶]
]
1 => array:7 [▶]
2 => array:7 [▶]
3 => array:7 [▶]
4 => array:7 [▶]
]
}
我想将嵌套的 status
值更新为 inactive
。我使用了 Laravel map
函数,但它似乎只适用于具有一层嵌套的 collections 。所以这个...
$this->deployments->map(function ($deployment) {
$deployment['spots'][0]['status'] = 'inactive';
});
dd($this->deployments);
...保持 $this->deployments
不变。
还尝试使用嵌套 map
函数在第二层获得 Call to a member function map() on array
异常,因为第二层和下一个嵌套层被视为数组...
有什么想法吗? 提前致谢。
使用 map
方法,您就快成功了。您将必须 return 在 $deployment
中所做的更改,并在最后执行 ->all()
以使用修改后的值更新集合。
更新单点:
$deployments = $deployments->map(function($deployment){
$deployment['spots'][0]['status'] = 'inactive';
return $deployment;
})->all();
更新所有景点:
$deployments = $deployments->map(function($deployment){
foreach($deployment['spots'] as &$spot){
$spot['status'] = 'inactive';
}
return $deployment;
})->all();
对于任何研究这个的人来说,一个更优雅的解决方案可能是:
更新单点:
$data = $deployments->all();
$deployments = data_set($data, 'spots.0.status', 'inactive');
更新所有景点:
$data = $deployments->all();
$deployments = data_set($data, 'spots.*.status', 'inactive');