【问题标题】:Fetch values from multiple json array urls从多个 json 数组 url 中获取值
【发布时间】:2021-01-14 00:37:29
【问题描述】:

我需要从 extern item-API json 数组中获取 [result]->[data]->[id]->xx 信息。我想将它们保存在 mysql 表(项目)中。

第一个 json 数组的示例 url:

https://eu.api.blizzard.com/data/wow/search/item?namespace=static-eu&orderby=id&_pageSize=1000&id=[1,]&_page=1&locale=de_DE&access_token=USPqoKWmdURvO1mmDeW5vRghI5dojO13XZ

您会在网址中看到 [1,]。这是我想从这里开始获取的最低项目 ID

一个 json 数组 url 可以显示的最大项目是 1000。API 有超过 170.000 个项目,我需要它们的特定 [data] [id]。 API 调用限制为每秒 100 次和每小时 36.000 次。

我的想法是从当前数组中获取 last [data] [id] 值。然后在下一个循环中,我将 1 添加到最后一个数组的 [data] [id] 值作为下一个循环的起点。以此类推。

在示例 url 中,最后一项 id 是 2429。所以在下一个循环中,2430 将是起点。

https://eu.api.blizzard.com/data/wow/search/item?namespace=static-eu&orderby=id&_pageSize=1000&id=[2430,]&_page=1&locale=de_DE&access_token=USPqoKWmdURvO1mmDeW5vRghI5dojO13XZ

这是我的代码。我不知道如何循环这个以及是否可以这样做。也许有更简单的解决方案。

 //**Decode JSON in PHP ARRAY**//

function getSslPage($url, $userAgent)
{
    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

    $result = curl_exec($ch);
    curl_close($ch);

    return json_decode($result, true);
}

$userAgent = 'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0';

//**GET the [DATA] [ID] value of the last KEY in the CURRENT array**//

$all_values = array_values($data['results']);
$last_value = end($all_values);

//**In the next LOOP the [DATA] [ID] VALUE should be +1 as the new starting point**//

$startingItem = $last_value['data']['id'] + 1;

$url = "https://eu.api.blizzard.com/data/wow/search/item?namespace=static-eu&orderby=id&_pageSize=1000&id=[$startingItem,]&_page=1&locale=de_DE&access_token=USPqoKWmdURvO1mmDeW5vRghI5dojO13XZ";

$data = getSslPage($url, $userAgent);

//** INSERT in database **//

foreach ($data['results'] as $entry) {

       $sqle= "REPLACE INTO `items`
                (`id`)
            VALUES
                ('{$entry['data']['id']}')";
}

【问题讨论】:

    标签: php arrays loops curl foreach


    【解决方案1】:

    如果您使用的是 PHP 版本 > 7.3,您可以使用 array_key_last() 检索最后一个索引键

    顺便说一下,您正在使用检索最后一个密钥

    end($all_values).

    注意该索引末尾的逗号 (,),您应该 trim 您的索引字符串仅包含数字,尝试使用

    $newkey = trim($key, ',')

    然后你可以用intval()检索它的int值

    $intnewkey = intval($newkey).

    现在您将能够增加您的索引

    $intnewkey++;,

    strval()返回字符串

    $newIndex = strval($intnewkey)

    然后再次将逗号附加到 API 调用的新值:

    $newIndexForAPI = $newIndex . ','

    【讨论】:

      猜你喜欢
      • 2014-04-21
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 2020-11-29
      • 2018-09-22
      • 1970-01-01
      • 1970-01-01
      • 2022-07-07
      相关资源
      最近更新 更多