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

如何将普通数组重构为PHP关联数组?

Convert Flat Path Array to Nested Associative Array in PHP

Problem

I need to convert a flat array where each element is a slash-separated path into a nested associative array that mirrors the path hierarchy. Here's my input and desired output:

Input Array:

$array = [ 
    't1/t1sub', 
    't1/t2sub', 
    't2/t1sub', 
    't3/t1sub', 
    't1/t4sub', 
    't4', 
    't1/t2sub/t1subsub', 
    't1/t2sub/t2subsub' 
];

Desired Output:

$target = [ 
    "t1" => [ 
        "t1sub", 
        "t2sub" => [ 
            "t1subsub", 
            "t2subsub" 
        ], 
        "t4sub", 
    ], 
    "t2" => [ 
        "t1sub", 
    ], 
    "t3" => [ 
        "t1sub", 
    ], 
    "t4" 
];

Solution

You can build this nested array by iterating over each path, splitting it into segments, and constructing the hierarchy step by step. Here's a working PHP function to do this:

function buildNestedPathArray(array $pathList): array {
    $nestedArray = [];

    foreach ($pathList as $path) {
        $segments = explode('/', $path);
        $currentLevel = &$nestedArray;

        foreach ($segments as $index => $segment) {
            $isLastSegment = $index === count($segments) - 1;

            if ($isLastSegment) {
                // Add as a leaf value if it's the end of the path
                $currentLevel[] = $segment;
            } else {
                // Create the segment as an array if it doesn't exist (or isn't already an array)
                if (!isset($currentLevel[$segment]) || !is_array($currentLevel[$segment])) {
                    $currentLevel[$segment] = [];
                }
                // Move down to the next level in the hierarchy
                $currentLevel = &$currentLevel[$segment];
            }
        }

        // Unset the reference to prevent accidental overwrites in future iterations
        unset($currentLevel);
    }

    return $nestedArray;
}

// Example usage
$inputArray = [ 
    't1/t1sub', 
    't1/t2sub', 
    't2/t1sub', 
    't3/t1sub', 
    't1/t4sub', 
    't4', 
    't1/t2sub/t1subsub', 
    't1/t2sub/t2subsub' 
];

$outputArray = buildNestedPathArray($inputArray);

// Verify the output
print_r($outputArray);

How This Works

  1. Split Paths: Each string is split into individual segments using explode('/', $path), turning something like t1/t2sub/t1subsub into ['t1', 't2sub', 't1subsub'].
  2. Traverse the Hierarchy: Using a reference variable ($currentLevel), we navigate through the nested array as we build it. For each segment:
    • If it's the last segment in the path, we add it as a value to the current array level.
    • If it's not the last segment, we ensure the segment exists as an array (creating it if needed) and then move our reference to that sub-array.
  3. Prevent Reference Leaks: Unsetting the reference after each path ensures we don't accidentally modify the wrong part of the array in subsequent iterations.

Edge Case Notes

  • If a path exists both as a leaf (like t1/t2sub) and as a parent for deeper paths (like t1/t2sub/t1subsub), the function automatically converts the leaf into a parent array to accommodate the deeper hierarchy—exactly matching your desired output.
  • Single-segment paths (like t4) are added directly as top-level values.

内容的提问来源于stack exchange,提问作者Matthias Hertel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:08:40