You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何扁平化含数组元素的集合?报错排查与解决

问题原因

你触发报错的核心原因是:array_merge(...$unflattened_array) 会将$unflattened_array中的每个元素直接作为array_merge的参数,但你的数组里混合了字符串和数组元素,而array_merge要求所有参数必须是数组类型,字符串不符合要求,因此抛出错误。

解决方案

方法1:利用Laravel集合自带的flatten()(推荐)

你一开始查询得到的$articles是Laravel集合,无需转成数组再处理,直接调用集合的flatten()方法就能一键扁平化:

$articles = DB::table('articles')
    ->where('is_published', 'true')
    ->pluck('category');

// 直接对集合扁平化后转数组
$flattened_array = $articles->flatten()->toArray();
dd($flattened_array);

flatten()会自动识别元素类型,不管是嵌套数组还是字符串,最终都会平铺为一维数组。

方法2:原生PHP处理数组

如果要基于转后的$unflattened_array处理,先把所有非数组元素包装成单元素数组,再用array_merge:

// 先将每个元素统一为数组类型
$normalized_items = array_map(function($item) {
    return is_array($item) ? $item : [$item];
}, $unflattened_array);

// 再合并所有数组
$flattened_array = array_merge(...$normalized_items);
dd($flattened_array);

方法3:用array_reduce累加合并

$flattened_array = array_reduce($unflattened_array, function($result, $item) {
    // 把当前元素转成数组后合并到结果里
    return array_merge($result, is_array($item) ? $item : [$item]);
}, []);
dd($flattened_array);

内容的提问来源于stack exchange,提问作者kamilfromxyz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 17:17:05