简体   繁体   English

如何遍历JSON响应?

[英]How to loop through a JSON response?

I use curl to get json, and the results from json are links, then curl to the link from the json results 我使用curl获取json,并且json的结果是链接,然后从json结果卷曲到链接

I tried using if () repeatedly but I don't think this is the right way to send / respond a lot 我尝试反复使用if(),但我认为这不是正确的发送/回复方式

the code that I use 我使用的代码

$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 ...
    }
}

You need to learn how to write a function... 您需要学习如何编写函数...

<?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;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM