14

I am trying to create an array like this in a loop:

$dataPoints = array(
    array('x' => 4321, 'y' => 2364),
    array('x' => 3452, 'y' => 4566),
    array('x' => 1245, 'y' => 3452),
    array('x' => 700, 'y' => 900), 
    array('x' => 900, 'y' => 700));

with this code

$dataPoints = array();    
$brands = array("COCACOLA","DellChannel","ebayfans","google",
    "microsoft","nikeplus","amazon"); 
foreach ($brands as $value) {
    $resp = GetTwitter($value);
    $dataPoints = array(
        "x"=>$resp['friends_count'],
        "y"=>$resp['statuses_count']);
}

but when loop completes my array looks like this:

Array ( [x] => 24 [y] => 819 ) 
nalply
  • 26,770
  • 15
  • 78
  • 101

3 Answers3

30

This is because you're re-assigning $dataPoints as a new array on each loop.

Change it to:

$dataPoints[] = array("x"=>$resp['friends_count'],"y"=>$resp ['statuses_count']);

This will append a new array to the end of $dataPoints

Hamish
  • 22,860
  • 8
  • 53
  • 67
1

use array_merge($array1,$array2) make it simple use two array one for use in iteration and another for storing the final result. checkout the code.

$dataPoints = array();  
$dataPoint = array();  

$brands = array(
    "COCACOLA","DellChannel","ebayfans","google","microsoft","nikeplus","amazon"); 
foreach($brands as $value){
    $resp = GetTwitter($value);
    $dataPoint = array("x"=>$resp['friends_count'],"y"=>$resp ['statuses_count']);
    $dataPoints = array_merge($dataPoints,$dataPoint);
}
jnthnjns
  • 8,962
  • 4
  • 42
  • 65
rajmohan
  • 1,618
  • 1
  • 15
  • 36
0

Every iteration you're overwriting $dataPoints variable, but you should add new elements to array...

$dataPoints[] = array("x"=>$resp['friends_count'],"y"=>$resp ['statuses_count']);

Kirzilla
  • 16,368
  • 26
  • 84
  • 129