How can PHP be optimized to efficiently calculate average prices based on time intervals within an array of market data?

To efficiently calculate average prices based on time intervals within an array of market data in PHP, we can use a combination of array functions like array_filter and array_column to filter the data based on the time intervals and then calculate the average price for each interval.

// Sample market data array
$marketData = [
    ['time' => '2022-01-01 08:00:00', 'price' => 100],
    ['time' => '2022-01-01 08:15:00', 'price' => 110],
    ['time' => '2022-01-01 08:30:00', 'price' => 120],
    ['time' => '2022-01-01 08:45:00', 'price' => 130],
    // Add more data here
];

// Define time intervals
$intervals = [
    ['start' => '08:00:00', 'end' => '08:15:00'],
    ['start' => '08:15:00', 'end' => '08:30:00'],
    ['start' => '08:30:00', 'end' => '08:45:00'],
    // Add more intervals here
];

// Calculate average prices for each interval
foreach ($intervals as $interval) {
    $filteredData = array_filter($marketData, function($data) use ($interval) {
        $time = strtotime($data['time']);
        return $time >= strtotime($interval['start']) && $time < strtotime($interval['end']);
    });

    $prices = array_column($filteredData, 'price');
    $averagePrice = array_sum($prices) / count($prices);

    echo "Average price for interval {$interval['start']} - {$interval['end']}: {$averagePrice}\n";
}