What are the advantages of processing data non-recursively before converting it into a recursive structure in PHP?

When processing data non-recursively before converting it into a recursive structure in PHP, it can help improve performance and reduce the risk of stack overflow errors. By processing the data in a non-recursive manner first, you can simplify the data structure and make it easier to work with before converting it into a recursive format.

// Non-recursive data processing
$flatData = [
    ['id' => 1, 'name' => 'Alice', 'parent_id' => null],
    ['id' => 2, 'name' => 'Bob', 'parent_id' => 1],
    ['id' => 3, 'name' => 'Charlie', 'parent_id' => 2],
    ['id' => 4, 'name' => 'David', 'parent_id' => 1]
];

// Convert flat data into a recursive structure
$recursiveData = [];
foreach ($flatData as $item) {
    $recursiveData[$item['id']] = $item;
}

foreach ($recursiveData as $id => &$item) {
    if ($item['parent_id'] !== null) {
        $recursiveData[$item['parent_id']]['children'][$id] = &$item;
        unset($recursiveData[$id]);
    }
}

// Output the recursive data structure
echo json_encode($recursiveData, JSON_PRETTY_PRINT);