Reputation: 1293
In a nutshell, I'm having problems printing an assoc array outside of a loop in PHP. I'm essentially looping over an array of campaign IDs which are substituted into the URL of a curl request (this is to retrieve an array of JSON from the server). I'm then using regex to retrieve the "base_bid" from this JSON. Ideally, I need to output a two-dimensional assoc array with ['id'] and ['base_bid'] keys like this:
Array ( [0] => Array ( [id] => 12311 [base_bid] => 0.8 ) [1] => Array ( [id] => 12322 [base_bid] => 0.4 ) )
The problem is that I can't access the complete assoc array outside of the loop as the values overlap meaning I get this output:
Array ( [id] => 11710821 [base_bid] => 3.8416 )
Here is my loop design:
for ($i=0; $i < count($campaigns); $i++) {
$ch = curl_init('https://api.appnexus.com/campaign?id='.$campaigns[$i].'');
$options = array(CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Authorization:'.$token[1].''));
curl_setopt_array($ch, $options);
$base = curl_exec($ch);
curl_close($ch);
preg_match('/"base_bid":([0-9\.]+)/', $base ,$bid);
$test['id'] = $campaigns[$i];
$test['base_bid'] = $bid[1];
};
echo print_r($test);
Does anybody know how I would be able to retrieve a two-dimensional array of IDs and base_bids in its entirety outside of my loop?
Any comments would be greatly appreciated!
Thanks,
Sam
Upvotes: 1
Views: 148
Reputation: 17417
You need to append to the $test array instead of overwriting the elements in it, e.g.
$test[] = array(
'id' => $campaigns[$i],
'base_bid' => $bid[1],
);
The [] operator adds a new element to the $test array each time, which should give you the structure you want.
Upvotes: 2