在 Laravel 6 中,操作多维数组时,使用引用传递以精简代码实现
1、现有的代码实现如下
<?php use Illuminate\Support\Arr; if (Arr::has($schema, 'sections')) { foreach ($schema['sections'] as $sectionKey => $section) { foreach ($section['blocks'] as $blockKey => $block) { if ($block['type'] == 'internal/size-chart/blocks/size-chart') { Arr::forget($schema, 'sections.' . $sectionKey . '.blocks.' . $blockKey); $blockOrderKey = array_search($blockKey, $section['block_order']); if ($blockOrderKey !== false) { Arr::forget($schema, 'sections.' . $sectionKey . '.block_order.' . $blockOrderKey); } } } Arr::set($schema, 'sections.' . $sectionKey . '.block_order', array_values(Arr::get($schema, 'sections.' . $sectionKey . '.block_order'))); } } return $schema;
2、使用引用传递以精简代码实现,可将 Arr::forget($schema, ‘sections.’ . $sectionKey . ‘.blocks.’ . $blockKey); 替换为:Arr::forget($section, ‘blocks.’ . $blockKey);
<?php use Illuminate\Support\Arr; if (Arr::has($schema, 'sections')) { foreach ($schema['sections'] as $sectionKey => &$section) { foreach ($section['blocks'] as $blockKey => $block) { if ($block['type'] == 'internal/size-chart/blocks/size-chart') { Arr::forget($section, 'blocks.' . $blockKey); $blockOrderKey = array_search($blockKey, $section['block_order']); if ($blockOrderKey !== false) { Arr::forget($section, 'block_order.' . $blockOrderKey); } } } Arr::set($section, 'block_order', array_values(Arr::get($section, 'block_order'))); } } return $schema;
近期评论