Получение API с помощью curl PHP - PullRequest
2 голосов
/ 04 августа 2020

Я хочу получить API из https://www.travel-advisory.info/api, тогда я уже написал свой код

  $curl = new CurlService();
  $response = $curl->to('https://www.travel-advisory.info/api')->get();
  throw_if(!$response, Exception::class, 'Terjadi kesalahan: Data tidak dapat diperoleh');      
  $data = json_decode($response);
  echo $data->data;

, так что это пример ответа от API

  "data": {
    "AD": {
      "iso_alpha2": "AD",
      "name": "Andorra",
      "continent": "EU",
      "advisory": {
        "score": 2.79999999999999982236431605997495353221893310546875,
        "sources_active": 4,
        "message": "",
        "updated": "2020-08-04 07:21:19",
        "source": "https://www.travel-advisory.info/andorra"
      }
    },
    "AE": {
      "iso_alpha2": "AE",
      "name": "United Arab Emirates",
      "continent": "AS",
      "advisory": {
        "score": 3.100000000000000088817841970012523233890533447265625,
        "sources_active": 7,
        "message": "",
        "updated": "2020-08-04 07:21:19",
        "source": "https://www.travel-advisory.info/united-arab-emirates"
      }
    },
    "AF": {
      "iso_alpha2": "AF",
      "name": "Afghanistan",
      "continent": "AS",
      "advisory": {
        "score": 5,
        "sources_active": 10,
        "message": "",
        "updated": "2020-08-04 07:21:19",
        "source": "https://www.travel-advisory.info/afghanistan"
      }
    },
    "AG": {
      "iso_alpha2": "AG",
      "name": "Antigua and Barbuda",
      "continent": "NA",
      "advisory": {
        "score": 3,
        "sources_active": 3,
        "message": "",
        "updated": "2020-08-04 07:21:19",
        "source": "https://www.travel-advisory.info/antigua-and-barbuda"
      }
    },
    "AI": {
      "iso_alpha2": "AI",
      "name": "Anguilla",
      "continent": "NA",
      "advisory": {
        "score": 3,
        "sources_active": 3,
        "message": "",
        "updated": "2020-08-04 07:21:19",
        "source": "https://www.travel-advisory.info/anguilla"
      }
    }
  }

мой вопрос в том, как фильтровать continent : "AS"? р

Ответы [ 3 ]

1 голос
/ 04 августа 2020
$data = json_decode($response, true)['data'];
print_r($this->continentFilter($data, 'AS'));

Функция будет иметь вид:

private function continentFilter(array $data, string $continent): array
{
    $filteredArray = [];
    foreach ($data as $item) {
        if ($item['continent'] === $continent) {
            $filteredArray = $item;

            break;
        }
    }

    return $filteredArray;
}
0 голосов
/ 04 августа 2020

вы можете использовать json_decode с флагом массива и array_filter метод следующим образом:

$data = (json_decode($response, true))['data'];

$as = array_filter($data, function($item) {
    return $item['continent'] === 'AS';
});

Также обратите внимание, что json, который вы даете в качестве примера выше, необходимо заключить в фигурные скобки. вместе, вот так:

{
  "data": {
  ...
}
0 голосов
/ 04 августа 2020

Вы можете l oop через каждый объект и pu sh к новому массиву, если значение континента совпадает с «AS».

Использование $key => $value позволяет вам сохранить индексы.

Пример:

$filtered = [];
foreach ( $data->data as $key => $value )
{
    if ( $value->continent === "AS" )
    {
        $filtered[$key] = $value;
    }
}

print_r($filtered);

Вы получите:

[AE] => stdClass Object
    (
        [iso_alpha2] => AE
        [name] => United Arab Emirates
        [continent] => AS
        [advisory] => stdClass Object
            (
                [score] => 3.1
                [sources_active] => 7
                [message] => 
                [updated] => 2020-08-04 07:21:19
                [source] => https://www.travel-advisory.info/united-arab-emirates
            )

    )

[AF] => stdClass Object
    (
        [iso_alpha2] => AF
        [name] => Afghanistan
        [continent] => AS
        [advisory] => stdClass Object
            (
                [score] => 5
                [sources_active] => 10
                [message] => 
                [updated] => 2020-08-04 07:21:19
                [source] => https://www.travel-advisory.info/afghanistan
            )

    )
    ...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...