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

Laravel中如何用点符号优雅扁平化多维数组?

Laravel中优雅扁平化多维数组的实现方式

当然有超优雅的实现方式!Laravel 不管是通过 Collections 还是全局辅助函数,都能轻松帮你把带层级的多维数组转换成键名带点符号的扁平化数组。

  • 使用 Laravel Collections 的 dot() 方法
    这是最贴合Laravel风格的做法,先把普通数组转成Collection实例,调用dot()方法就能自动将层级键用点连接,最后再转回数组即可:
$array = ['parent' => ['childA' => "value", 'childB' => "value"]];

$flattenedArray = collect($array)->dot()->toArray();

// 最终结果:
// ['parent.childA' => "value", 'parent.childB' => "value"]

这个方法还支持处理更深层级的嵌套数组,完全不用自己写复杂的递归逻辑,比如三层嵌套的场景:

$array = [
    'parent' => [
        'childA' => ['grandchild' => 'deep value'],
        'childB' => "value"
    ]
];

$flattened = collect($array)->dot()->toArray();
// 输出:['parent.childA.grandchild' => 'deep value', 'parent.childB' => "value"]
  • 使用全局辅助函数 array_dot()
    如果不想绕一圈转成Collection,Laravel 还提供了直接操作数组的全局辅助函数array_dot(),效果和上面完全一致:
$array = ['parent' => ['childA' => "value", 'childB' => "value"]];

$flattenedArray = array_dot($array);

这两种方式都是Laravel原生支持的,代码简洁易读,完全符合“优雅实现”的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:32:31