1

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

1
  • why you reject my editing Commented Apr 11, 2016 at 7:38

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for helping me understand this iainn, I can use the array outside of my loop now!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.