2010-12-21 18 views
11

Sto cercando di creare un array come questo in un ciclo:Creare un array multidimensionale in un ciclo

$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)); 

con questo codice

$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']); 
} 

ma quando ciclo completato il mio allineamento simile a questa:

Array ([x] => 24 [y] => 819) 

risposta

23

Questo perché si sta ri-assegnazione di $dataPoints come un nuovo array per ogni ciclo.

modificarla in:

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

Questo aggiungerà un nuovo array alla fine della $dataPoints

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

Ogni iterazione si sta sovrascrivendo variabile $ datapoints, ma si dovrebbe aggiungere nuovi elementi alla matrice ...

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

2

usa array_merge($array1,$array2) per semplificare l'uso di due array uno per l'uso in iterazione e un altro per la memorizzazione del risultato finale. verifica il codice.

$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); 
} 
Problemi correlati