如何使用foreach循环PHP数组

时间:2010-06-12 06:16:32

标签: php arrays loops

如何使用foreach循环遍历$ Result?

<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or die("Could not connect: " . mysql_error());
mysql_select_db("mydb");

$Query  = mysql_query("SELECT * FROM mytable");
$Result = array( );

while ($Row = mysql_fetch_array ( $Query) ) {
    $Result [ ] = $Row;  
}

mysql_free_result($Query);

print_r ($Result);

?>

我的想法非常模糊:

<?php

foreach ($Result )
{
 echo $row[fname] . ' ' . $row[lname] . ' ' $row[email];
}

?>

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:0)

如下所示

foreach($Result as $row){
   $fname=$row['fname'];
   // etc...
}

答案 1 :(得分:0)

为什么要对该数组采用间接方式?你可以简单地做到这一点:

$Query  = mysql_query("SELECT * FROM mytable");

while ($Row = mysql_fetch_array ( $Query) ) {
  echo $Row[fname] . ' ' . $Row[lname] . ' ' $Row[email]; 
}

mysql_free_result($Query);

答案 2 :(得分:0)

$link = mysqli_link('host', 'user', 'pass', 'db');
$query = 'SELECT * FROM mytable';
$result = mysqli_query($link, $query)
while ($row =  mysqli_fetch_assoc($result)) {
  $out .= $row['fname'] . ' ' . $row['lname'] . ' ' . $row['email'];
}
echo $out;