【问题标题】:Create a multidimensional array in a loop在循环中创建多维数组
【发布时间】:2011-05-28 16:24:28
【问题描述】:

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

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

【问题讨论】:

    标签: php arrays loops multidimensional-array foreach


    【解决方案1】:

    使用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);
    }
    

    【讨论】:

      【解决方案2】:

      每次迭代都会覆盖 $dataPoints 变量,但应该向数组添加新元素...

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

      【讨论】:

        【解决方案3】:

        这是因为您在每个循环中将 $dataPoints 重新分配为一个新数组。

        改成:

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

        这将在$dataPoints的末尾追加一个新数组

        【讨论】:

          猜你喜欢
          • 2014-10-25
          • 2019-12-29
          • 2014-06-26
          • 2013-04-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-12
          相关资源
          最近更新 更多