如何遍历JSON响应?

时间:2019-05-25 03:03:34

标签: php json

我使用curl来获取json,并且json的结果是链接,然后从json结果中卷曲到链接

我尝试反复使用if(),但我认为这不是发送/回复大量内容的正确方法

我使用的代码

$first_url = 'https://example.com/?exmaple-json-kadsdbkbznczsa1sdaf==';
$curl = curl($first_url);
$result = json_decode($curl, true);
$comments = $result['data']['comments'];
$status_next = $result['data']['status_next_url'];
$next_url = $result['data']['next_url'];
print json_encode($comments);
if ($status_next = true) {
    $curl = curl($next_url);
    $result = json_decode($curl, true);
    $comments = $result['data']['comments'];
    $status_next = $result['data']['status_next_url'];
    $next_url = $result['data']['next_url'];
    print json_encode($comments);
    if ($status_next = true) {
        $curl = curl($next_url);
        $result = json_decode($curl, true);
        $comments = $result['data']['comments'];
        $status_next = $result['data']['status_next_url'];
        $next_url = $result['data']['next_url'];
        print json_encode($comments);

    //and the next will always be the same ...
    }
}

1 个答案:

答案 0 :(得分:0)

您需要学习如何编写函数...

<?php

    function getPaginatedOutput($hash, $cursor = 0) {

        // Init URL
        $url = "https://example.com/?query_hash=" . trim($hash);

        // Add cursor/paginator if supplied
        if ((int) $cursor > 0) {
            $url .= "&after=" . (int) $cursor;
        }

        // Create curl handle and get data
        $curl = curl($url);

        // Pull data
        $result = json_decode($curl, true);
        $comments = $result['data']['shortcode_media']['edge_media_to_parent_comment']['edges'];
        $statuspage = $result['data']['shortcode_media']['edge_media_to_parent_comment']['page_info']['has_next_page'];
        $cursor = $result['data']['shortcode_media']['edge_media_to_parent_comment']['page_info']['end_cursor'];

        // Return values for next call
        return [
            'comments'  => json_encode($comments, JSON_PRETTY_PRINT),
            'cursor'    => (int) $cursor,
            'status'    => $statuspage,
        ];
    }

    // You then call the function with a hash and an optional cursor
    $hashes = [
        "97b41c52301f77ce508f55e66d17620e",
        "97b41c52301f77ce508f55e66d17620"
    ];

    $cursor = 0;
    foreach ($hashes as $hash) {
        $output = getPaginatedOutput($hash, $cursor);
        $cursor = $output['cursor'];
        print $output['comments'];
        if ($output['status'] != true) {
           break;
        }
    }