2010-12-21 68 views
11

我想在一個循環中創建一個這樣的數組創建多維數組:在一個循環中

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

與此代碼

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

但是當循環完成我的數組是這樣的:

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

回答

23

這是因爲你重新分配$dataPoints作爲每個循環的新數組。

將其更改爲:

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

這將新的數組追加到的$dataPoints

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

末你覆蓋$的數據點變量每次迭代,但你應該加入新的元素陣列...

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

2

使用array_merge($array1,$array2)可以簡單地使用兩個數組一個用於迭代,另一個用於存儲最終結果。簽出代碼。

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