php 在循环中创建多维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4497149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a multidimensional array in a loop
提问by r1400304
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 )
回答by Hamish
This is because you're re-assigning $dataPoints
as a new array on each loop.
这是因为您$dataPoints
在每个循环中重新分配为一个新数组。
Change it to:
将其更改为:
$dataPoints[] = array("x"=>$resp['friends_count'],"y"=>$resp ['statuses_count']);
This will append a new array to the end of $dataPoints
这将追加一个新数组到末尾 $dataPoints
回答by rajmohan
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.
use array_merge($array1,$array2)
make it simple 使用两个数组,一个用于迭代,另一个用于存储最终结果。签出代码。
$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);
}
回答by Kirzilla
Every iteration you're overwriting $dataPoints variable, but you should add new elements to array...
每次迭代都会覆盖 $dataPoints 变量,但您应该向数组添加新元素...
$dataPoints[] = array("x"=>$resp['friends_count'],"y"=>$resp ['statuses_count']);
$dataPoints[] = array("x"=>$resp['friends_count'],"y"=>$resp ['statuses_count']);