如何将>分隔的多级分类字符串转换为无限层级嵌套关联数组
分类路径转无限层级嵌套关联数组解决方案
推荐方案:引用传址实现(无递归、性能更高)
该方案无需递归,时间复杂度仅为O(n),无层级上限,是生产环境最优选择:
function buildNestedCategories(string $pathStr, string $delimiter = '>'): array { // 分割路径、去除分类名前后空格、过滤空分类 $categoryList = array_filter(array_map('trim', explode($delimiter, $pathStr))); $nestedArray = []; // 引用指针跟踪当前操作的嵌套层级 $currentLevel = &$nestedArray; foreach ($categoryList as $categoryName) { // 若当前层级不存在该分类则初始化空数组 if (!isset($currentLevel[$categoryName])) { $currentLevel[$categoryName] = []; } // 指针下移到当前分类的子层级 $currentLevel = &$currentLevel[$categoryName]; } return $nestedArray; }
使用示例
$categoryPath = "Category 1 > SubCategory 2 > SubSubCategory 3 > SubSubSubCategory 4"; $result = buildNestedCategories($categoryPath); // 验证结构 var_dump(isset($result['Category 1']['SubCategory 2']['SubSubCategory 3']['SubSubSubCategory 4'])); // 输出 bool(true)
可选方案:递归实现
如果更习惯递归写法可以用该方案,注意PHP默认递归深度限制为100层,超深层级场景不推荐:
function buildNestedCategoriesRecursive(array $categoryList, int $currentIndex = 0): array { if ($currentIndex >= count($categoryList)) { return []; } return [ $categoryList[$currentIndex] => buildNestedCategoriesRecursive($categoryList, $currentIndex + 1) ]; }
使用示例
$categoryPath = "Category 1 > SubCategory 2 > SubSubCategory 3"; $categoryList = array_filter(array_map('trim', explode('>', $categoryPath))); $result = buildNestedCategoriesRecursive($categoryList);
内容的提问来源于stack exchange,提问作者Adrian Emil Tudorache
相关产品推荐
相关产品推荐

