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条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题