如何将一维数组转换为下一个元素作为前一个元素子项的嵌套数组?
Got it, I see what you're trying to do here—turn a simple flat array into a chain of nested objects where each item wraps the next one in a child key. The array_merge_recursive function isn’t going to help here because it’s designed to merge arrays with overlapping keys, not build this kind of sequential nested structure.
Solution 1: Reverse Loop (Most Efficient)
The easiest way to build this nested structure is to work backwards from the end of your flat array. This way, each item can take the previously built nested chunk as its child value.
// Your original flat array $flatArray = ['A', 'B', 'C', 'D']; $nestedResult = null; // Iterate from last item to first foreach (array_reverse($flatArray) as $value) { $nestedResult = [ 'value' => $value, 'names' => [ '1' => $value, '2' => $value ], 'child' => $nestedResult ]; } // Output the result print_r($nestedResult);
How this works:
- We start with
$nestedResultset tonull(you can change this to an empty array[]if you prefer the finalchildto be empty instead of null). - For each item in the reversed array, we create a new array with the required
value,names, and setchildto whatever$nestedResultalready holds. - By the end of the loop,
$nestedResultwill be the fully nested structure you want.
Solution 2: Recursive Approach
If you prefer a recursive method (great for smaller arrays), you can write a function that builds the structure one level at a time:
function buildNestedChain($flatArray, $currentIndex = 0) { // Stop recursion if we've reached the end of the array if (!isset($flatArray[$currentIndex])) { return null; // Or return [] for an empty final child } $currentValue = $flatArray[$currentIndex]; return [ 'value' => $currentValue, 'names' => [ '1' => $currentValue, '2' => $currentValue ], 'child' => buildNestedChain($flatArray, $currentIndex + 1) ]; } // Usage $flatArray = ['A', 'B', 'C']; $nestedResult = buildNestedChain($flatArray); print_r($nestedResult);
Note on recursion:
Be careful with very large arrays here—PHP has a recursion depth limit, so a loop is safer for big datasets.
Why array_merge_recursive doesn't work
As you noticed, array_merge_recursive merges arrays by combining values with the same key. For example, if you had two arrays with a names key, it would merge those into a single array. But it can't create this sequential, nested "chain" structure where each item points to the next via a child key.
内容的提问来源于stack exchange,提问作者Andrii Kovalenko

