2010-12-21 71 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); 
}