[英]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.