MYYA
我确信它可以真正优化:<?php $arGiven = [ // add the root category [ 'category_id' => 96, 'parent_id' => 0, 'id_path' => '', 'level' => 0, ], [ 'category_id' => 100, 'parent_id' => 107, 'id_path' => '', 'level' => 0, ], [ 'category_id' => 106, 'parent_id' => 96, 'id_path' => '', 'level' => 0, ], [ 'category_id' => 107, 'parent_id' => 106, 'id_path' => '', 'level' => 0, ] ]; $level = 0; $parentLevelIds = [0]; do { $level++; $nextParentLevelIds = []; $arGiven = array_map(function($value) use($level, $parentLevelIds, &$nextParentLevelIds, $arGiven) { if (in_array($value['parent_id'], $parentLevelIds)) { $path = ''; if ($value['parent_id'] !== 0) { $parent = array_filter($arGiven, function($parentSearchValue) use ($value) { return $parentSearchValue['category_id'] == $value['parent_id']; }); if (!empty($parent)) { $path = array_shift($parent)['id_path']; } } $value['level'] = $level; $value['id_path'] = empty($path) ? $value['category_id'] : ( $path . '/' . $value['category_id'] ); $nextParentLevelIds[] = $value['category_id']; } return $value; }, $arGiven); $parentLevelIds = $nextParentLevelIds; $hasLevel0 = !empty(array_filter($arGiven, function($value) { return $value['level'] == 0; })); } while ($hasLevel0);