What are some best practices for organizing and grouping data in PHP arrays for statistical analysis?

When organizing and grouping data in PHP arrays for statistical analysis, it is important to structure the data in a way that makes it easy to perform calculations and analysis. One common approach is to use associative arrays where the keys represent different categories or groups, and the values are arrays containing the data points belonging to each category. This allows for easy access to specific data points and simplifies the process of calculating statistics for each group.

// Sample data array
$data = [
    ['category' => 'A', 'value' => 10],
    ['category' => 'B', 'value' => 20],
    ['category' => 'A', 'value' => 15],
    ['category' => 'B', 'value' => 25],
];

// Organize data into groups based on category
$groupedData = [];
foreach ($data as $item) {
    $category = $item['category'];
    $value = $item['value'];
    
    if (!isset($groupedData[$category])) {
        $groupedData[$category] = [];
    }
    
    $groupedData[$category][] = $value;
}

// Calculate statistics for each group
foreach ($groupedData as $category => $values) {
    $mean = array_sum($values) / count($values);
    $min = min($values);
    $max = max($values);
    
    echo "Category: $category\n";
    echo "Mean: $mean\n";
    echo "Min: $min\n";
    echo "Max: $max\n\n";
}