3

您好,我正在尝试在 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>';

我没有得到所有的值,只是得到一个值,请帮助 thx

4

3 回答 3

9

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);
}
于 2012-05-23T06:12:24.100 回答
0
function mail_detail($mail_detail){
    $returnArr = array();
    $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)){
        $returnArr[] = $result;
    }
    return $returnArr;

}

这样一来,您返回所有返回的内容,因为您将其推送到一个数组中,并且当您的循环完成时,将返回整个数组。因为就像 xbones 说的那样,return 会破坏你的循环!

于 2012-05-23T06:15:08.053 回答
0

harinder,Function(mysql_fetch_array($data))返回一个数组。这意味着您$result是一个数组,因此当您收到$resultat view 页面时,您必须使用foreach如下所示提取它:

foreach($result as $item)
 {
   echo $item->user(<-here you have to write the column name ,that you want to retrieve)
 } 

因此,您可以在数组中获得所有结果。

于 2012-05-23T07:04:33.020 回答