从多个json数组网址中获取值

问题描述

我需要从外部项目API json数组中获取 [结果]-> [数据]-> [id]-> xx 信息。我想将它们保存在MysqL表(项目)中。

一个json数组的示例网址:

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数组网址最多可以显示1000个项目。API有超过170.000个项目,我需要它们的特定[数据] [id]。 API调用限制为每秒100和每小时36.000。

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

在示例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,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版本是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 . ','