修改数组中的对象正在更改会话值
Modifying object in array is changing the session value
我在 PHP Laravel 中有以下代码,其中包含对象数组。每个对象都有 2 个属性。身份证和姓名。整个对象都保存在会话中。然后保存后,我从数组中的每个对象中删除 id。这也是在修改session。
我是不是做错了什么?
$array = [];
$obj = new \stdClass();
$obj->id = "1";
$obj->name = "Test";
array_push($array, $obj);
$request->session()->put('val', $array);
foreach($array as $key => $val) {
unset($array[$key]->id);
}
echo "<pre>";
print_r($request->session()->get('val'));
echo "</pre>";
在这里,我注意到 id 属性从会话中消失了。
出现问题是因为正在操作对象的同一副本。要解决此问题,您需要 clone
对象,然后取消设置并发送响应以保持会话中的数据完好无损。
$cloned_data = [];
foreach($array as $key => $val) {
$new_obj = clone $val;
unset($new_obj->id);
$cloned_data[] = $new_obj;
}
print_r($cloned_data);
为了仅将名称发送到前端,您可以使用 collection pluck 来获取仅包含名称的新数组
$dataForFrontend = collect($array)->pluck('name')->all();
This is changing the view of data to be send to front end. [0] => 'Test'
如果您需要按名称键入它 - 类似于 [0]['name'] => 'Test'
$dataForFrontend = collect($data)->map(
fn($item) => ['name' => $item->name]
)->all();
如果需要将数组元素保留为原始类型的对象,与@nice_dev的解决方案基本相同
$dataForFrontend = collect($array)->map(function($item) {
$clone = clone $item;
unset($clone->id);
return $clone;
})->all();
将数组元素保留为对象——不是原始类型而是 std 的对象 class
$dataForFrontend = collect($data)->map(
fn($item) => (object)['name' => $item->name]
)->all();
我在 PHP Laravel 中有以下代码,其中包含对象数组。每个对象都有 2 个属性。身份证和姓名。整个对象都保存在会话中。然后保存后,我从数组中的每个对象中删除 id。这也是在修改session。
我是不是做错了什么?
$array = [];
$obj = new \stdClass();
$obj->id = "1";
$obj->name = "Test";
array_push($array, $obj);
$request->session()->put('val', $array);
foreach($array as $key => $val) {
unset($array[$key]->id);
}
echo "<pre>";
print_r($request->session()->get('val'));
echo "</pre>";
在这里,我注意到 id 属性从会话中消失了。
出现问题是因为正在操作对象的同一副本。要解决此问题,您需要 clone
对象,然后取消设置并发送响应以保持会话中的数据完好无损。
$cloned_data = [];
foreach($array as $key => $val) {
$new_obj = clone $val;
unset($new_obj->id);
$cloned_data[] = $new_obj;
}
print_r($cloned_data);
为了仅将名称发送到前端,您可以使用 collection pluck 来获取仅包含名称的新数组
$dataForFrontend = collect($array)->pluck('name')->all();
This is changing the view of data to be send to front end. [0] => 'Test'
如果您需要按名称键入它 - 类似于 [0]['name'] => 'Test'
$dataForFrontend = collect($data)->map(
fn($item) => ['name' => $item->name]
)->all();
如果需要将数组元素保留为原始类型的对象,与@nice_dev的解决方案基本相同
$dataForFrontend = collect($array)->map(function($item) {
$clone = clone $item;
unset($clone->id);
return $clone;
})->all();
将数组元素保留为对象——不是原始类型而是 std 的对象 class
$dataForFrontend = collect($data)->map(
fn($item) => (object)['name' => $item->name]
)->all();