[英]Create a multidimensional array 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));
用這個代碼
$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 )
這是因為您在每個循環$dataPoints
重新分配為新數組。
將其更改為:
$dataPoints[] = array("x"=>$resp['friends_count'],"y"=>$resp ['statuses_count']);
這將在$dataPoints
的末尾附加一個新數組
使用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);
}
每次迭代都要覆蓋$ dataPoints變量,但是你應該向數組添加新元素......
$dataPoints[] = array("x"=>$resp['friends_count'],"y"=>$resp ['statuses_count']);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.