php - 在循环中创建多维数组

标签 php arrays loops multidimensional-array foreach

我正在尝试在循环中创建这样的数组:

$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 的末尾

关于php - 在循环中创建多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4497149/

相关文章:

php - php上的多次 Sprite 图像

javascript - 使用带有对象的 Javascript 数组填充 HTML 表格

java - 迭代器从第一个元素开始

php - 在搜索框中输入内容时自动显示用户名?

php - 从数组中删除所有值,同时保持键不变

c++ - 为什么我的二维数组的第二行从 RAM 中获取随机值?

java - 为什么我的 Jersey ClientResponse 不为空,但可用返回 0?

python - 为列表的最后一项运行不同的函数

c# - 将 2 个 foreach 循环减少到一个 linq 查询中

php - MYSQL在屏幕上分段打印日期