Laravel 11中如何向JSON字段添加值并生成扁平数组?
修复Laravel中JSON字段添加值导致的嵌套数组问题
问题根源是array_push会把传入的数组当作单个元素插入目标数组,而非合并元素。你的代码中array_push($this->selectedCurrencies, array_values($userOption->value))将旧值数组作为子元素添加,最终形成嵌套结构。
以下是两种修复方案:
方案1:使用array_merge合并数组
// 先获取已有的值,兜底处理null情况 $existingValues = $userOption->value ?? []; // 合并已有值和新选择的货币 $this->selectedCurrencies = array_merge($existingValues, $this->selectedCurrencies); // 可选:去重并重新索引数组(如果需要避免重复值) $this->selectedCurrencies = array_values(array_unique($this->selectedCurrencies)); // 赋值并保存 $userOption->value = $this->selectedCurrencies; $userOption->save();
方案2:使用PHP展开运算符(PHP 7.4+支持,更简洁)
$existingValues = $userOption->value ?? []; // 展开两个数组合并为扁平数组 $this->selectedCurrencies = [...$existingValues, ...$this->selectedCurrencies]; // 可选:去重并重新索引 $this->selectedCurrencies = array_values(array_unique($this->selectedCurrencies)); $userOption->value = $this->selectedCurrencies; $userOption->save();
关键说明
- 必须确保
$userOption->value处理为数组:Laravel的JSON字段如果未设置默认值,可能返回null,因此用?? []兜底。 - 若不需要去重,可去掉
array_unique步骤。
内容的提问来源于stack exchange,提问作者mstdmstd
相关产品推荐
相关产品推荐

