Sio Sio - 17 days ago 5
PHP Question

Put JSON response value into new array (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

Answer

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.