while循环vs foreach循环

时间:2016-10-21 02:56:46

标签: php loops foreach

我试图在excel中打印它,但我不明白为什么 foreach循环给我一个警告:非法字符串偏移但是在 while循环中它运行顺利

这是 while循环

EDITED

include 'db.php';
$sql = "SELECT * FROM customer";
$result = mysql_query($sql);
$excel = array();

while($row = mysql_fetch_array($result)){
    $wew = $row["fname"]."\t".$row["lname"]."\t".$row["email"];
    array_push($excel,$wew);
}

echo implode("\n",array_values($excel));

这是我的 foreach循环

include 'db.php';
$sql = "SELECT * FROM customer";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$excel = array();

foreach($row as $r){
    $wew = $r["fname"]."\t".$r["lname"]."\t".$r["email"];
    array_push($excel,$wew);
}

echo implode("\n",array_values($excel));

我试图理解它,但无法找到解决这个问题的方法。

1 个答案:

答案 0 :(得分:2)

$r属于string类型,而不是array所以:

foreach($row as $r){
    $wew = $row["fname"]."\t".$row["lname"]."\t".$row["email"];
    array_push($excel,$wew);
}

$wew = "";
foreach($row as $r){
    $wew .= $row["fname"]."\t".$row["lname"]."\t".$row["email"]; 
}
array_push($excel,$wew);