你好,我正在尝试在 php 中使用 while 循环创建函数,但无法在这里写入我的代码
function mail_detail($mail_detail){
$data= mysql_query("select * from messages where messages.to = '$mail_detail' and to_viewed = 0 ORDER BY messages.id DESC");
while ($result= mysql_fetch_array($data)){
return $result;
}
}
输出是
$mail_detail= mail_detail($userid)
echo '<li class="read">
<a href="#">
<span class="message">'. $mail_detail['title'].'</span>
<span class="time">
January 21, 2012
</span>
</a>
</li>';
我没有获得所有值,只是获得一个值,请帮忙
谢谢
The return
语句正在终止循环并退出函数。
要获取所有值,请将它们添加到循环中的数组中,然后返回该数组。像这样:
$results = array();
while ($result = mysql_fetch_array($data)) {
$results[] = $result;
}
return $results;
在接收数组的一侧
$msgArray = mail_detail($mail_detail);
foreach($msgArray as $msg) {
//use $msg
}
补充一下,一个函数只能返回一次(除了一些你不应该担心的特殊情况)。因此,函数第一次遇到 return 语句时,它会返回值并退出。
这个功能的return
通常可以为您带来优势。例如:
function doSomething($code = NULL)
{
if ($code === NULL) {
return false;
}
//any code below this comment will only be reached if $code is not null
// if it is null, the above returns statement will prevent control from reaching
// this point
writeToDb($code);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)