How can PHP be used to condense and combine data from similar rows in an array?

When working with arrays in PHP, it is common to have multiple rows of data that are similar and need to be condensed or combined. One way to achieve this is by iterating through the array and merging the similar rows based on a specific key or condition. This can be done using a loop and checking for similarities between rows before combining them into a single row.

// Sample array with similar rows
$data = [
    ['id' => 1, 'name' => 'John', 'age' => 25],
    ['id' => 2, 'name' => 'Jane', 'age' => 30],
    ['id' => 1, 'name' => 'Doe', 'age' => 35],
    ['id' => 3, 'name' => 'Alice', 'age' => 28]
];

// Combine rows with similar IDs
$combinedData = [];
foreach ($data as $row) {
    $id = $row['id'];
    if (isset($combinedData[$id])) {
        $combinedData[$id]['name'] .= ', ' . $row['name'];
        $combinedData[$id]['age'] += $row['age'];
    } else {
        $combinedData[$id] = $row;
    }
}

// Output the condensed data
print_r(array_values($combinedData));