php 使用 mysql_fetch_array() 和 foreach() 而不是 while()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3442895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use mysql_fetch_array() with foreach() instead of while()
提问by Ibrahim Azhar Armar
i want to know how do we convert the following code to work with foreach
我想知道我们如何将以下代码转换为与 foreach 一起使用
$query_select = "SELECT * FROM shouts ORDER BY id DESC LIMIT 8;";
$result_select = mysql_query($query_select) or die(mysql_error());
while($row = mysql_fetch_array($result_select)) {
$ename = stripslashes($row['name']);
$eemail = stripcslashes($row['email']);
$epost = stripslashes($row['post']);
$eid = $row['id'];
$grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70";
echo ('<img src = "' . $grav_url . '" alt="Gravatar">'.'<br/>');
echo $eid . '<br/>';
echo $ename . '<br/>';
echo $eemail . '<br/>';
echo $epost . '<br/><br/><br/><br/>';
回答by Bang Dao
You can code like this:
你可以这样编码:
$query_select = "SELECT * FROM shouts ORDER BY id DESC LIMIT 8;";
$result_select = mysql_query($query_select) or die(mysql_error());
$rows = array();
while($row = mysql_fetch_array($result_select))
$rows[] = $row;
foreach($rows as $row){
$ename = stripslashes($row['name']);
$eemail = stripcslashes($row['email']);
$epost = stripslashes($row['post']);
$eid = $row['id'];
$grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70";
echo ('<img src = "' . $grav_url . '" alt="Gravatar">'.'<br/>');
echo $eid . '<br/>';
echo $ename . '<br/>';
echo $eemail . '<br/>';
echo $epost . '<br/><br/><br/><br/>';
}
As you can see, it's still need a loop while to get data from mysql_fetch_array
如您所见,从 mysql_fetch_array 获取数据仍然需要一个循环
回答by cincodenada
There's not a good way to convert it to foreach, because mysql_fetch_array()
just fetches the next result from $result_select
. If you reallywanted to foreach, you could do pull all the results into an array first, doing something like the following:
将其转换为 foreach 并不是一个好方法,因为mysql_fetch_array()
只是从$result_select
. 如果你真的想 foreach,你可以先把所有的结果拉到一个数组中,执行如下操作:
$result_list = array();
while($row = mysql_fetch_array($result_select)) {
result_list[] = $row;
}
foreach($result_list as $row) {
...
}
But there's no good reason I can see to do that - and you still have to use the while loop, which is unavoidable due to how mysql_fetch_array()
works. Why is it so important to use a foreach()?
但是我认为没有充分的理由这样做 - 而且您仍然必须使用 while 循环,由于mysql_fetch_array()
工作原理,这是不可避免的。为什么使用 foreach() 如此重要?
EDIT:If this is just for learning purposes: you can't convert this to a foreach
. You have to have a pre-existing array to use a foreach()
instead of a while()
, and mysql_fetch_array()
fetches one result per call - there's no pre-existing array for foreach()
to iterate through.
编辑:如果这只是为了学习目的:您不能将其转换为foreach
. 您必须有一个预先存在的数组才能使用 aforeach()
而不是 a while()
,并且mysql_fetch_array()
每次调用获取一个结果 - 没有预先存在的数组可供foreach()
迭代。
回答by MooGoo
To use foreach
would require you have an array that contains every row from the query result. Some DB libraries for PHP provide a fetch_all
function that provides an appropriate array but I could not find one for mysql
(however the mysqliextension does) . You could of course write your own, like so
使用foreach
需要你有一个包含查询结果中每一行的数组。一些 PHP 的 DB 库提供了一个fetch_all
函数,该函数提供了一个适当的数组,但我找不到mysql
(但是mysqli扩展可以)。你当然可以自己写,像这样
function mysql_fetch_all($result) {
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
return $rows;
}
However I must echo the "why?" Using this function you are creating two loops instead of one, and requring the entire result set be loaded in to memory. For sufficiently large result sets, this could become a serious performance drag. And for what?
但是我必须回应“为什么?” 使用此函数,您将创建两个循环而不是一个循环,并要求将整个结果集加载到内存中。对于足够大的结果集,这可能会成为严重的性能拖累。为了什么?
foreach (mysql_fetch_all($result) as $row)
vs
对比
while ($row = mysql_fetch_array($result))
while
is just as concise and IMO more readable.
while
同样简洁,IMO 更具可读性。
EDITThere is another option, but it is pretty absurd. You could use the Iterator Interface
编辑还有另一种选择,但它非常荒谬。您可以使用迭代器接口
class MysqlResult implements Iterator {
private $rownum = 0;
private $numrows = 0;
private $result;
public function __construct($result) {
$this->result = $result;
$this->numrows = mysql_num_rows($result);
}
public function rewind() {
$this->rownum = 0;
}
public function current() {
mysql_data_seek($this->result, $this->rownum);
return mysql_fetch_array($this->result);
}
public function key() {
return $this->rownum;
}
public function next() {
$this->rownum++;
}
public function valid() {
return $this->rownum < $this->numrows ? true : false;
}
}
$rows = new MysqlResult(mysql_query($query_select));
foreach ($rows as $row) {
//code...
}
In this case, the MysqlResult
instance fetches rows only on request just like with while
, but wraps it in a nice foreach-able package. While you've saved yourself a loop, you've added the overhead of class instantiation and a boat load of function calls, not to mention a good deal of added code complexity.
在这种情况下,MysqlResult
实例只在请求时获取行,就像 with 一样while
,但将它包装在一个很好的 foreach-able 包中。虽然您为自己节省了一个循环,但您增加了类实例化的开销和大量函数调用,更不用说大量增加的代码复杂性了。
But you asked if it could be done without using while
(or for
I imagine). Well it canbe done, just like that. Whether it shouldbe done is up to you.
但是您问是否可以在不使用while
(或for
我想象)的情况下完成。嗯,它可以做到,就像那样。是否应该完成取决于您。
回答by just somebody
the most obvious way to make foreach
a possibility includes materializing the whole resultset in an array, which will probably kill you memory-wise, sooner or later. you'd need to turn to iterators to avoid that problem. see http://www.php.net/~helly/php/ext/spl/
实现foreach
可能性的最明显方法包括将整个结果集具体化为一个数组,这可能迟早会在内存方面杀死您。你需要求助于迭代器来避免这个问题。见http://www.php.net/~helly/php/ext/spl/
回答by Hi I'm SID
You could just do it like this
你可以这样做
$query_select = "SELECT * FROM shouts ORDER BY id DESC LIMIT 8;";
$result_select = mysql_query($query_select) or die(mysql_error());
foreach($result_select as $row){
$ename = stripslashes($row['name']);
$eemail = stripcslashes($row['email']);
$epost = stripslashes($row['post']);
$eid = $row['id'];
$grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70";
echo ('<img src = "' . $grav_url . '" alt="Gravatar">'.'<br/>');
echo $eid . '<br/>';
echo $ename . '<br/>';
echo $eemail . '<br/>';
echo $epost . '<br/><br/><br/><br/>';
}