How can PHP be effectively used to calculate and display the sum of units for each user and their subordinates?

To calculate and display the sum of units for each user and their subordinates, we can use a recursive function to traverse the user hierarchy and sum up the units for each user and their subordinates. We can store the user hierarchy in an array or database table with parent-child relationships, and then use a recursive function to calculate the sum of units for each user and their subordinates.

<?php
// Function to calculate the sum of units for a user and their subordinates
function calculateUnits($userId, $users) {
    $sum = $users[$userId]['units'];
    
    if(isset($users[$userId]['subordinates'])) {
        foreach($users[$userId]['subordinates'] as $subordinateId) {
            $sum += calculateUnits($subordinateId, $users);
        }
    }
    
    return $sum;
}

// Example user hierarchy data
$users = [
    1 => ['units' => 10, 'subordinates' => [2, 3]],
    2 => ['units' => 5, 'subordinates' => [4]],
    3 => ['units' => 3],
    4 => ['units' => 2]
];

// Calculate and display the sum of units for each user and their subordinates
foreach($users as $userId => $userData) {
    $totalUnits = calculateUnits($userId, $users);
    echo "User $userId has a total of $totalUnits units.\n";
}
?>