在php中使用多维数组外循环范围

时间:2011-08-07 22:14:46

标签: php arrays loops multidimensional-array scope

我也想在循环外使用arrData数组,如何在循环范围外声明它,好像现在它没有正确填充

  $SQL = "SELECT * FROM DailyData WHERE User='$_SESSION[userID]'"; 
    $result = mysql_query($SQL); 
    $i=0; 
    // trying this
    $arrData= array();
    $arrData []= array();
    while($row = mysql_fetch_array($result)) 
    { 
    echo $row['Score'] . " " . $row['Date']; 
    $arrData[i][1]=$row['Date']; 
    $arrData[i][2]=$row['Score']; 
    $i++; 
    echo "<br />"; 
    }

2 个答案:

答案 0 :(得分:2)

$arrDatawhile循环范围之外可用。

看起来你忘记了美元符号:

$arrData[i][1]=$row['Date']; 
$arrData[i][2]=$row['Score']; 

应该是

$arrData[$i][1]=$row['Date']; 
$arrData[$i][2]=$row['Score']; 

在原文中,PHP认为你的意思是$arrData['i'],这意味着你继续写$arrData['i'][1]$arrData['i'][2] - 但是,你正在递增$i,所以你想要使用该变量 - $arrData[$i][1]$arrData[$i][2]

答案 1 :(得分:1)

我想这可能就是你要找的东西:

  $SQL = "SELECT * FROM DailyData WHERE User='$_SESSION[userID]'"; 
  $result = mysql_query($SQL); 
  $arrData= array();

  while($row = mysql_fetch_array($result)) 
  { 
    $arrData[]=$row;
    //you can also do some output here if you want
  }

  //arrData is now available outside the while-loop
  foreach($arrData as $row) {
    echo $row['Score'] . ' ' . $row['Date'] . '<br />'; 
  }