Как ускорить запрос и обработку АПИ?

Есть код

<?php
$cache_ttl = 21600; // время жизни кэша в секундах
$cache_file_airlines = "tmp/airlines.data";
$cache_file_products = "tmp/products.data";
$map = function ($array, $from, $to)
{
    $result = [];
    if (!empty($array) && is_array($array))
    {
        foreach ($array as $element)
        {
            $key = $element[$from] ? : null;
            $value = $element[$to] ? : null;
            if ($key && $value)
            {
                $result[$key] = $value;
            }
        }
    }
    return $result;
};
if (file_exists($cache_file_airlines) && (time() - filemtime($cache_file_airlines)) < $cache_ttl)
{
    // берём кэшированные данные
    $get_airlines = file_get_contents($cache_file_airlines);
}
else
{
    $get_airlines = file_get_contents('/json/airlines.json');
    file_put_contents($cache_file_airlines, $get_airlines);
}
$airlines = $map(json_decode($get_airlines, true) , 'iata', 'name');

if (file_exists($cache_file_products) && (time() - filemtime($cache_file_products)) < $cache_ttl)
{
    // берём кэшированные данные
    $response = file_get_contents($cache_file_products);
}
else
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.travelpayouts.com/v1/prices/cheap?origin=MOW&destination=AER&limit=30&token=********");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "X-Access-Token: **********"
    ));
    $response = curl_exec($ch);
    curl_close($ch);

    file_put_contents($cache_file_products, $response);
}
$products = json_decode($response, true);
$replace_value = function ($key, $val) use ($airlines)
{
    $response = $val;
    switch ($key)
    {
        case 'airline':
            $response = $airlines[$val];
        break;
    }
    return $response;
} ?>

 <div id="kurorty" class="container" style="margin-top: 20px;">
 <div class="table-responsive"><h2>Авиабилеты Москва Адлер</h2><table id="table" class="table table-hover">
    <thead>
      <tr>
        <th style="text-align: center;"> Пункт отправления</th>
        <th style="text-align: center;">Пункт назначения </th>
        <th class="mob" style="text-align: center;"> Авиакомпания</th> <th style="text-align: center;">Цена, р.</th> <th class="mob" style="text-align: center;">Дата вылета</th>
<th class="mob" style="text-align: center;">Обратная дата</th>
<th> </th>
      </tr>
    </thead><tbody>
<?php
if (isset($products['data']) && is_array($products['data']))
{
    foreach ($products['data'] as $key => $data)
    {
        foreach ($data as $destination => $row)
        {
            if (preg_match('/[A-Z]{3}/i', $key))
            {
?>
<tr>
<td>&nbsp; <?php echo 'Москва'; ?>&nbsp;</td>
        <td>&nbsp; <?php echo 'Адлер'; ?>&nbsp;</td>
      <td class="mob"><img src="https://pics.avs.io/100/40/<?=$row['airline'] ?>.webp" data-src="https://pics.avs.io/100/40/<?=$row['airline'] ?>.webp" class="lazyload"/></td>
<td><?php echo $replace_value('price', $row['price']); ?>&nbsp;  RUB &nbsp; </td>
<td class="mob"><?php echo $replace_value('departure_at', substr($row['departure_at'], 0, 10)); ?></td>
<td class="mob"><?php echo $replace_value('return_at', substr($row['return_at'], 0, 10)); ?></td>
      <td><a rel="nofollow" rel="noopener" role="button" alt="авиабилеты Москва <?php echo $replace_value('destination', $key); ?>" title="Москва <?php echo $replace_value('destination', $key); ?>" href="/flights/?origin_iata=MOW&destination_iata=<?=$key ?>&depart_date=<?=substr($row['departure_at'], 0, 10) ?>&return_date=<?=substr($row['return_at'], 0, 10) ?>&adults=1&children=0&infants=0&trip_class=0&marker=87111&with_request=true">Поиск</a></td></tr>
<?php
            }
        }
    }
}
?>

Результатом выполнения кода является ответ

{"success":true,"data":{"AER":{"0":{"price":3570,"airline":"UT","flight_number":4267,"departure_at":"2020-05-19T16:15:00Z","return_at":"2020-05-26T05:00:00Z","expires_at":"2020-03-03T07:38:49Z"},"1":{"price":4615,"airline":"UT","flight_number":579,"departure_at":"2020-03-25T01:45:00Z","return_at":"2020-03-27T12:55:00Z","expires_at":"2020-03-03T07:05:27Z"},"2":{"price":10742,"airline":"5N","flight_number":273,"departure_at":"2020-04-30T17:00:00Z","return_at":"2020-05-25T12:05:00Z","expires_at":"2020-03-01T06:20:02Z"},"3":{"price":21185,"airline":"U6","flight_number":277,"departure_at":"2020-06-19T09:30:00Z","return_at":"2020-06-30T21:45:00Z","expires_at":"2020-03-03T02:27:55Z"}}},"error":null,"currency":"rub"}

Обработка с моей стороны проходит долго или цикл нарушен или повторный цикл идет, не могу разобраться. Буду рад помощи!


Ответы (0 шт):