带while循环的函数php [英] function php with while loop

查看:160
本文介绍了带while循环的函数php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我正在尝试使用while循环在PHP函数,但不能写这里是我的代码

 函数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 [标题]< /跨度>
< span class =time>
2012年1月21日
< / span>
< / a>
< / li>';

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

解决方案

return 语句终止您的循环并退出函数。



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

  $ results = array(); 

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

返回$ results;

接收数组

  $ msgArray = mail_detail($ mail_detail); 

foreach($ msgArray as $ msg){
//使用$ msg
}

为了补充,函数只能返回一次(除了一些你不应该担心的特殊情况)。因此,您的函数第一次遇到return语句时,它会返回值并退出。



的这个功能返回

 函数doSomething($ code = NULL)
{
if($ code == = NULL){
return false;
}

//只有$ code不为空时,才会到达此注释下方的任何代码
//如果它为null,则上述返回语句将阻止控件达到
//此点

writeToDb($ code);
}


Hello i am trying to make function with while loop in php but cant getting write here is my code

 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;
    }

}

and out put is

$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>';

i am not getting all values just getting one value please help thx

解决方案

The return statement is terminating your loop and exiting the function.

To get all values, add them to an array in the loop, and then return the array. Like this:

$results = array();

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

return $results;

on the side that receives the array

$msgArray = mail_detail($mail_detail);

foreach($msgArray as $msg) {
    //use $msg
}

To add on, a function is only able to return once (except for some special circumstances that you should not worry about). Therefore, the first time your function comes across a return statement, it returns the value and exits.

This functionality of return can often be used to your advantage. For example:

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);
}

这篇关于带while循环的函数php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆