dongne1560 2016-11-22 22:36
浏览 74
已采纳

将JSON响应值放入新数组(PHP)

I’m trying to use the Yelp API. In order to get the information I need, I first need to call the Yelp Search API, extract the IDs of the venues, and the use the IDs to call the Yelp Business API to drill down to the info I need.

As I’m doing quite a few of these API calls I’m using curl_multi and so I need to send in my data in an array. I have the first call to the Yelp Search API and I am able to see the IDs being returned. However, I am then trying to put those IDs into a new array to use in the second curl_multi to the Yelp Business API. I’m trying to use array_push but I just can’t get it to work.

Here is my code:

    (EDIT)//A for loop to get the first 20 results   
    for ($i = 0; $i < 20; $i++) {
    // $results contains this search results as an associative array
    $results = reset(json_decode(curl_multi_getcontent($ch[$i]), true));

    //I set up 2 arrays, the $idArray to use in the 2nd API call and $testNull
    $idArray = array();
    $testNull = array();

   //the JSON response is decoded previously and here I go through the first 20 results
    for($j = 0; $j < 20; $j++){
        //Here I put the ID of each venue into $busID
        $busID = $results[$j]['id'];
        //In case the result is null I have set up this if statement
        if(!empty($busID)){
            //This is echoing out the IDs of the venues correctly    
            echo $busID;
            //and here the problem lies - just can't get the IDs in $idArray
            array_push($idArray, $busID);
            }else{
                //I set this up just to test NUll responses from the 1st API call.
                array_push($testNull, $busID);
            }
    }
}
    var_dump($idArray);
    var_dump($testNull);

As I said in my comments, echoing $busID does indeed give me the IDs from the 1st Yelp API call, but var_dump of $idArray just returns an array with 20 NULL values.

Can anyone shed some light?

Thanks

  • 写回答

2条回答 默认 最新

  • dongxun5349 2016-11-22 23:02
    关注

    Inside another loop, you will still see the vardumps. This section of code works...see this sandbox link:

    http://sandbox.onlinephpfunctions.com/code/ddc4084713ae8ac15783ac653466524556b4169a

    But inside another loop, your $idArray may be being reset to empty.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度