【问题标题】:Put JSON response value into new array (PHP)将 JSON 响应值放入新数组 (PHP)
【发布时间】:2016-11-22 22:36:03
【问题描述】:

我正在尝试使用 Yelp API。为了获得我需要的信息,我首先需要调用 Yelp Search 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);

正如我在 cmets 中所说,回显 $busID 确实为我提供了第一次 Yelp API 调用的 ID,但 $idArray 的 var_dump 只返回一个包含 20 个 NULL 值的数组。

谁能解释一下?

谢谢

【问题讨论】:

  • 改为$idArray[] = $busID
  • 感谢 Erevald,我已经尝试过了,但不幸的是它也不起作用。
  • 对我来说一切都很好...3v4l.org/kb95I
  • 这之后的任何事情都只是猜测,因为您提供的代码似乎可以正常工作。我要冒昧地问一下,这段代码是否包含在函数或其他东西中并且函数范围有问题? PHP 不与函数外部定义的变量共享函数内部定义的变量。这意味着默认情况下,在函数中修改的变量不会在所述函数之外更改。
  • 感谢乔纳森的帮助,这段代码确实包含在一个函数中,但是我没有尝试从外部使用任何变量,因此范围不是问题。不过有一件事……这个 for 循环在另一个 for 循环中。可能更容易编辑我的原始帖子以显示我的意思......

标签: php arrays json for-loop array-push


【解决方案1】:

在另一个循环中,您仍然会看到 vardumps。这部分代码有效...请参阅此沙箱链接:

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

但在另一个循环中,您的 $idArray 可能被重置为空。

【讨论】:

  • 感谢 WEBjuju,当我从外部 for 循环中删除数组声明时,它确实有效!
【解决方案2】:

您确实意识到您的$idArray 对象是在每次新的“迭代”时创建的。也许最后一次迭代有空值?而var_dump 只打印最后一个数组对象(在循环完成之后)——因为转储在循环之外

移动你的数组:

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

在循环的顶部:

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

【讨论】:

  • 是的,我现在...谢谢 Maciej。我感谢所有帮助的人。
猜你喜欢
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 2022-07-11
  • 1970-01-01
  • 2011-02-20
  • 2011-08-09
  • 2021-08-30
  • 1970-01-01
相关资源
最近更新 更多