What are some common use cases for building arrays recursively in PHP?
Building arrays recursively in PHP is commonly used when dealing with hierarchical data structures such as nested categories, menus, or tree-like data. This approach allows for creating complex multi-dimensional arrays by iterating over nested elements and adding them to the array recursively. This can simplify the code and make it more readable when dealing with nested data.
function buildNestedArray($data, $parentId = null) {
$result = [];
foreach ($data as $item) {
if ($item['parent_id'] == $parentId) {
$children = buildNestedArray($data, $item['id']);
if (!empty($children)) {
$item['children'] = $children;
}
$result[] = $item;
}
}
return $result;
}
// Example usage
$data = [
['id' => 1, 'name' => 'Parent 1', 'parent_id' => null],
['id' => 2, 'name' => 'Child 1', 'parent_id' => 1],
['id' => 3, 'name' => 'Child 2', 'parent_id' => 1],
['id' => 4, 'name' => 'Grandchild 1', 'parent_id' => 2],
];
$nestedArray = buildNestedArray($data);
print_r($nestedArray);