@sochi-russia

API ошибка в получении данных. Высвечивается Array, как исправить?

Есть код
<?php

$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;
};

$airlines = $map(json_decode(file_get_contents('http://site.com/json/airlines.json'), true), 'iata', 'name');

$cit=json_decode(file_get_contents("http://site.com/json/cities.json")); $cities=array(); foreach($cit as $val) { if(property_exists($val->name_translations,"ru")) $cities[$val->code]=$val->name_translations->ru;}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://othersite.com/v1/city-directions?origin=REN&token=xxxxxxx");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Access-Token: xxxxx"));
$response = curl_exec($ch);
curl_close($ch);

$products=json_decode($response,true);




$replace_value = function($key, $val) use ($cities, $airlines){
    $response = $val;
    switch($key){case 'destination':
            $response = $cities[$val];break;
            case 'origin':
            $response = $cities[$val];break;
        case 'airline':
            $response = $airlines[$val];
            break;
    }
    return $response;
}

?>
<table class="features-table">
<thead style="background: rgba(2, 69, 141, 0.46) none repeat scroll 0% 0%; color: rgb(255, 255, 255);">
    <tr>
              <th class="views-field views-field-field-logo-fid">
        Пункт отправления     </th>
              <th class="views-field views-field-tid">
          Пункт назначения      </th>
              <th class="views-field views-field-tid-1">
  Цена, р.        </th>
              <th class="views-field views-field-field-napravlenie-value">Пересадки
                  </th>
              <th class="views-field views-field-field-cenaot-value">
          Авиакомпания       </th>
              <th class="views-field views-field-field-prodsgas-value">№ рейса</th>
              <th class="views-field views-field-field-prodsgapo-value">
         Дата вылета     </th>
              <th class="views-field views-field-field-perelets-value">Обратно</th>
              <th class="views-field views-field-field-pereletpo-value">
</th></tr>
</thead>
<?php
if(isset($products['data']) && is_array($products['data'])) {
foreach ($products['data'] as $key => $data) {
?>
<tr>
<?php
foreach ($data as $field => $val) {
if ('expires_at' == $field) {
?>
<td><a rel="nofollow" href="http://site.com/searches/new?origin_iata=REN&destination_iata=<?=$data['destination']?>&depart_date=<?=substr($data['departure_at'], 0, 10)?>&return_date=<?=substr($data['return_at'], 0, 10)?>&adults=1&children=0&infants=0&trip_class=0&marker=marker&with_request=true">Купить</a></td>
<?php
} else {
?>
<td><?php echo $replace_value($field, $val); ?></a></td>
<?php
}
}
?>
</tr>
<?php
}
}
?>
</table>


Вот сам ответ апи в случае запроса через адресную строку, с ним код не работает
{"success": true, "data": {"AAQ":{"1":{"price":15450,"airline":"SU","flight_number":5831,"departure_at":"2016-02-13T19:30:00Z","return_at":"2016-02-21T17:55:00Z","expires_at":"2016-02-10T08:36:26Z"},"2":{"price":18275,"airline":"SU","flight_number":1245,"departure_at":"2016-03-17T05:55:00Z","return_at":"2016-03-28T12:05:00Z","expires_at":"2016-02-09T09:28:27Z"},"3":{"price":21798,"airline":"SU","flight_number":1245,"departure_at":"2016-03-17T05:55:00Z","return_at":"2016-03-28T12:05:00Z","expires_at":"2016-02-09T09:28:27Z"}},"ABA":{"1":{"price":98040,"airline":"R2","flight_number":5833,"departure_at":"2016-02-10T09:00:00Z","return_at":"2016-02-15T09:55:00Z","expires_at":"2016-02-10T06:24:28Z"}},"ADD":{"2":{"price":131269,"airline":"SU","flight_number":1245,"departure_at":"2016-02-10T05:55:00Z","return_at":"2016-02-20T23:59:00Z","expires_at":"2016-02-09T15:21:53Z"}},"AER":{"1":{"price":81152,"airline":"SU","flight_number":1245,"departure_at":"2016-05-01T05:55:00Z","return_at":"2016-05-22T10:45:00Z","expires_at":"2016-02-10T17:35:28Z"}}}}


При запросе через php появляется Array.
А вот с этим ответом код работает
{"success":true,"data":{"AAQ":{"origin":"REN","destination":"AAQ","price":15450,"transfers":1,"airline":"SU","flight_number":5831,"departure_at":"2016-02-13T19:30:00Z","return_at":"2016-02-21T17:55:00Z","expires_at":"2016-02-10T08:36:26Z"},"AER":{"origin":"REN","destination":"MOW","price":9250,"transfers":0,"airline":"FV","flight_number":6754,"departure_at":"2016-06-14T07:40:00Z","return_at":"2016-06-14T09:30:00Z","expires_at":"2016-02-10T06:09:23Z"},"SIP":{"origin":"REN","destination":"SIP","price":15450,"transfers":1,"airline":"SU","flight_number":5833,"departure_at":"2016-02-22T09:00:00Z","return_at":"2016-02-29T08:40:00Z","expires_at":"2016-02-11T04:10:37Z"},"SVX":{"origin":"REN","destination":"SVX","price":18429,"transfers":0,"airline":"O7","flight_number":85,"departure_at":"2016-02-15T07:00:00Z","return_at":"2016-02-19T15:10:00Z","expires_at":"2016-02-10T15:51:10Z"}},"error":null,"currency":"rub"}


Подскажите пожалуйста как исправить? Заранее спасибо, с уважением.
  • Вопрос задан
  • 689 просмотров
Пригласить эксперта
Ответы на вопрос 2
@Silm
Некое API и куча корявого кода...

Отлаживайте код. Для начала посмотрите дамп ответа перед началом его обработки.
Если в дампе есть ожидаемые данные, значит ищите ошибку в последующей обработке, если ожидаемых данных нет, значит ошибка в запросе, ищите ошибку в нем.
Ответ написан
@pikls23
err_net_array как исправить ошибку
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы