功能php与while循环

Har*_*der 3 php function

你好我想在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;
    }

}
Run Code Online (Sandbox Code Playgroud)

出来就是

$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>';
Run Code Online (Sandbox Code Playgroud)

我没有得到所有价值只是获得一个值请帮助thx

xbo*_*nez 9

return语句将终止您的循环并退出该函数.

要获取所有值,请将它们添加到循环中的数组中,然后返回该数组.像这样:

$results = array();

while ($result = mysql_fetch_array($data)) {
    $results[] = $result;   
}

return $results;
Run Code Online (Sandbox Code Playgroud)

在接收阵列的一侧

$msgArray = mail_detail($mail_detail);

foreach($msgArray as $msg) {
    //use $msg
}
Run Code Online (Sandbox Code Playgroud)

要添加,函数只能返回一次(除了一些您不应该担心的特殊情况).因此,当您的函数第一次遇到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);
}
Run Code Online (Sandbox Code Playgroud)