如何使用 JSON 数据将所有下一页数据包含在单个 PHP foreach 循环中


How to include all next page data within single PHP foreach loop using JSON data

我有一个 JSON 文件,将我限制为每页 50 个项目,而这一个项目总共有 818 个项目。

我可以单独从前 50 个中提取数据。我想知道是否有人知道如何拉取所有其他页面,以便它们都在一个 php 请求中。

有没有人碰巧对一个函数或 if 语句有一个想法可以帮助解决这个问题?

结果数量有限的 json 示例片段(将显示 50 个):

{
    "count": 818, 
    "max_per_page": 50, 
    "current_page": 1, 
    "links": [
        {
            "href": "http://domain.com/?page=2", 
            "rel": "next"
        }, 
        {
            "href": "http://domain.com/", 
            "rel": "prev"
        }
    ], 
    "results": [
        {
            "id": "1", 
            "href": "http://domain.com/23385", 
            "product_line": "A", 
            "departures_start_date": "2015-01-01", 
            "departures_end_date": "2017-12-24"
        }, 
        {
            "id": "2", 
            "href": "http://domain.com/22760", 
            "product_line": "B", 
            "departures_start_date": "2015-01-01", 
            "departures_end_date": "2017-12-16"
        }, 
        {
            "id": "3", 
            "href": "http://domain.com/22790", 
            "product_line": "C", 
            "departures_start_date": "2015-01-01", 
            "departures_end_date": "2017-12-30"
        }, 
    ]
}

假设您使用 file_get_contents 检索数据,您可以尝试以下操作:

$array = array();
$page = 1;
while( $data = file_get_contents( '/Your/Path/Here?page=$page++' ) )
{
    $json = json_decode( $data, True );                                   #01
    foreach( $json['results'] as $row ) $array[] = $row;
}

在循环结束时,数组将包含所有元素:

[
    [
        "id": "1", 
        "href": "http://domain.com/23385", 
        (...)
    ], 
    [
        "id": "2", 
        "href": "http://domain.com/22760", 
        (...)
    ], 
    (...) 
]

如果您更喜欢对象而不是数组,则可以省略True (#01),然后每一行都可以通过 $row->id 而不是 $row['id']