PHP如何遍历此api的页面?

时间:2016-10-12 03:41:36

标签: php json

所以基本上我试图得到这个api上每个页面的AveragePrice的总和。现在它只获得第一页我已经尝试过的东西只能让它继续无休止地崩溃。下面是我的代码,1页工作。

我真的不确定如何让它循环浏览页面并得到每一页的总和。

ValueError

1 个答案:

答案 0 :(得分:0)

您可以通过查看正在使用的API查找要查找的页数来获得更好的答案。你想循环,直到你达到最大页面。您的请求结果中应该有一个值,告诉您您已经要求提供一个不存在的页面(即没有更多结果)。如果您可以获得total number of results to search for,那么您可以使用for循环作为限制。

//Change the function to accept the page number as a variable
function getRap($userId, $i){
            $url = sprintf("https://www.roblox.com/Trade/InventoryHandler.ashx?userId=" . $userId . "&filter=0&page=" . $i . "&itemsPerPage=14");

//work out how many pages it takes to include your total items
// ceil rounds a value up to next integer.
// ceil(20 / 14) = ceil(1.42..) == 2 ; It will return 2 and you will look for two pages
$limit = ceil($totalItems / $itemsPerPage);

// Then loop through calling the function passing the page number up to your limit.
for ($i = 0; $i < $limit; $i++) {
    getRap($userId, $i);
}

如果您无法获得项目总数,则可以在未发生失败状态时循环

// look for a fail state inside your getRap()
function getRap($userId, $i) {
    if ($result = error) { //you will have to figure out what it returns on a fail
        $tooMany = TRUE;
    }
}

for ($i = 0; $tooMany !== TRUE ; $i++) {
    getRap($userId, $i);
}

编辑:查看我的答案,在函数中查找失败状态的形式很差(由于此情况下变量的范围,因此无法工作)。您可以来回传递变量,但我会将该部分留给您。

要获得总数,请确保您的函数不打印结果(echo $rap),但将其返回以供进一步使用。

完整示例

<?php       
function getRap($userId, $i){
    $url = sprintf("https://www.roblox.com/Trade/InventoryHandler.ashx?userId=" . $userId . "&filter=0&page=" . $i . "&itemsPerPage=25");
    $results = file_get_contents($url);
    $json = json_decode($results, true);
    if ($json['msg'] == "Inventory retreived!") {
        $data = $json['data']['InventoryItems'];                    
        $rap = 0;

        foreach($data as $var) {
            $rap += $var['AveragePrice']; 
        }

        return $rap;
    } else {
        return FALSE;
    }
}

$total = 0;
$userId = 1;
for ($i = 0; $i < 1000 /*arbitrary limit to prevent permanent loop*/ ; $i++) {
    $result = getRap($userId, $i);
    if ($result == FALSE) {
        $pages = $i;
        break;
    } else {
        $total += getRap($userId, $i);
    }
}
echo "Total value of $total, across $pages pages";
?>
相关问题