【发布时间】: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