如何将普通数组重构为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
- Split Paths: Each string is split into individual segments using
explode('/', $path), turning something liket1/t2sub/t1subsubinto['t1', 't2sub', 't1subsub']. - 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.
- 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 (liket1/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
相关产品推荐
相关产品推荐

