Laravel/PHP多维数组扁平化:自定义层级展开方案问询
数组扁平化需求与解决方案
问题背景
当前存在如下结构的数组:
array:1 [ "blocks" => array:3 [ 0 => array:1 [ "component" => "TextColumns" ] 1 => array:2 [ 0 => array:1 [ "component" => "TextColumns" ] 1 => array:1 [ "component" => "TextColumns" ] ] 2 => array:1 [ "component" => "TextColumns" ] ] ]
需要将其转换为blocks为一维数组的结构:
array:1 [ "blocks" => array:4 [ 0 => array:1 [ "component" => "TextColumns" ] 1 => array:1 [ "component" => "TextColumns" ] 2 => array:1 [ "component" => "TextColumns" ] 3 => array:1 [ "component" => "TextColumns" ] ] ]
使用array_flatten或Laravel的->flatten()会过度扁平化,得到不符合需求的结果:
array:1 [ "blocks" => array:3 [ 0 => array:1 [ "component" => "TextColumns" ] 1 => array:2 [ 0 => "TextColumns" 1 => "TextColumns" ] 2 => array:1 [ "component" => "TextColumns" ] ] ]
补充源码:header和footer返回单个组件数组,content返回组件数组的集合,合并后需要展开content使blocks成为一维数组:
protected static function header(): array { return [ 'component' => 'TextColumns', ]; } protected static function content(): array { return [ [ 'component' => 'TextColumns', ], [ 'component' => 'TextColumns', ], ]; }
当前合并代码:
dd([ 'blocks' => [ static::header(), static::content(), static::footer(), ], ]);
解决方案
方案1:Laravel环境下指定深度扁平化
使用Laravel的Arr::flatten方法,通过第二个参数指定扁平化深度为1,仅展开第一层嵌套的数组:
use Illuminate\Support\Arr; $blocks = Arr::flatten([ static::header(), static::content(), static::footer(), ], 1); dd(['blocks' => $blocks]);
方案2:手动遍历合并(无框架依赖)
手动遍历原始数组,判断元素类型并展开合并:
$rawBlocks = [ static::header(), static::content(), static::footer(), ]; $blocks = []; foreach ($rawBlocks as $item) { if (is_array($item) && isset($item[0]) && is_array($item[0])) { $blocks = array_merge($blocks, $item); } else { $blocks[] = $item; } } dd(['blocks' => $blocks]);
方案3:用array_reduce简化合并逻辑
通过array_reduce实现更简洁的数组合并:
$rawBlocks = [ static::header(), static::content(), static::footer(), ]; $blocks = array_reduce($rawBlocks, function ($carry, $item) { return is_array($item) && count($item) > 0 && is_array($item[0]) ? array_merge($carry, $item) : array_merge($carry, [$item]); }, []); dd(['blocks' => $blocks]);
内容的提问来源于stack exchange,提问作者user1469914
相关产品推荐
相关产品推荐

