簡體   English   中英

將JSON響應值放入新數組(PHP)

[英]Put JSON response value into new array (PHP)

我正在嘗試使用Yelp API。 為了獲取我需要的信息,我首先需要調用Yelp搜索API,提取場所的ID,然后使用這些ID調用Yelp Business API來深入了解我所需的信息。

由於我正在執行許多此類API調用,因此我使用curl_multi,因此我需要將數據發送到數組中。 我是第一次調用Yelp Search API,並且能夠看到返回的ID。 但是,然后我試圖將這些ID放入新數組中,以在Yelp Business API的第二個curl_multi中使用。 我正在嘗試使用array_push,但我無法使其正常工作。

這是我的代碼:

    (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);

就像我在評論中說的那樣,回顯$ busID確實確實給了我來自第一個Yelp API調用的ID,但是$ idArray的var_dump僅返回具有20個NULL值的數組。

誰能闡明一些想法?

謝謝

在另一個循環中,您仍然會看到草稿。 此部分代碼有效...請參閱此沙盒鏈接:

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

但是在另一個循環中,您的$ idArray可能被重置為空。

您確實意識到$idArray對象是在每個新的“ iteration”上創建的。 也許最后一次迭代具有空值? var_dump僅打印最后一個數組對象(在循環完成之后)-因為轉儲在循環外部

移動數組:

$idArray = array();
$testNull = array();

在循環的頂部,這樣:

$idArray = array();
$testNull = array();
for ($i = 0; $i < 20; $i++) {
   ....
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM