首页 > 解决方案 > 从多个 json 数组 url 中获取值

问题描述

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

第一个 json 数组的示例 url:

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

您会在 url 中看到[1,] 。这是我要开始获取的最小项目 ID 。

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

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

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

https://eu.api.blizzard.com/data/wow/sea​​rch/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']}')";
}

标签: phparraysloopscurlforeach

解决方案


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

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

end($all_values).

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

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

然后您可以使用intval()检索其 int 值

$intnewkey = intval($newkey).

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

$intnewkey++;,

使用strval()返回字符串

$newIndex = strval($intnewkey)

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

$newIndexForAPI = $newIndex . ','


推荐阅读