PHP实现为多维数组的每个子数组添加层级(level)字段
Solution for Adding Level Depth to Multidimensional Array Nodes
To add a level key to each node (subarray with id/parentid) in your nested array, you can use a recursive function that traverses the hierarchy and assigns the appropriate depth level. Here's how to do it in PHP:
Step-by-Step Code Implementation
function addLevelToNodes(&$nodes, $level = 1) { foreach ($nodes as &$node) { // Check if we're dealing with a node (has an 'id' key) if (is_array($node) && isset($node['id'])) { // Assign the current level to this node $node['level'] = $level; // Look for any nested arrays containing child nodes foreach ($node as &$childCollection) { if (is_array($childCollection)) { // Recursively process child nodes with incremented level addLevelToNodes($childCollection, $level + 1); } } } } }
How to Use This Function
Modify the array in place:
// Your original multidimensional array $originalArray = [ [ 'id' => 1, 'parentid' => null, [ 'id' => 101, 'parentid' => 1 ] ], [ 'id' => 2, 'parentid' => null, [ 'id' => 161, 'parentid' => 2, 'children' => [ [ 'id' => 300, 'parentid' => 161 ] ] ] ] ]; // Apply the function to add levels addLevelToNodes($originalArray);Keep the original array intact:
If you don't want to modify the original array, create a copy first:$newArray = $originalArray; addLevelToNodes($newArray);
What This Does
- Top-level nodes (like the ones with
id:1andid:2) getlevel:1. - Direct children of those nodes (like
id:101andid:161) getlevel:2. - Nested children (like
id:300underid:161) getlevel:3, and so on for deeper levels. - The function automatically handles both numeric-indexed child arrays and named keys like
children—any array containing nodes will be processed recursively.
Example Output
After running the function, your array will look like this:
[ [ 'id' => 1, 'parentid' => null, 'level' => 1, [ 'id' => 101, 'parentid' => 1, 'level' => 2 ] ], [ 'id' => 2, 'parentid' => null, 'level' => 1, [ 'id' => 161, 'parentid' => 2, 'level' => 2, 'children' => [ [ 'id' => 300, 'parentid' => 161, 'level' => 3 ] ] ] ] ]
内容的提问来源于stack exchange,提问作者Nibboro
相关产品推荐
相关产品推荐

