2012-05-23 54 views
3

你好,我是努力使功能與while循環在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; 
    } 

} 

進出放功能PHP是

$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

回答

8

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

我試圖從該表(消息)中獲取所有值,如果返回正在終止我應該用什麼來代替返回,所以此函數使用while循環。 – Harinder

+0

看到我的編輯答案 – xbonez

+0

感謝您的幫助,但它不是出於某種原因...功能mail_detail($ mail_detail)工作{ \t \t $數據=請求mysql_query(「從郵件中選擇*其中messages.to = '$ mail_detail' 和to_viewed = 0 ORDER BY messages.id DESC「); \t $ results = array(); \t while($ result = mysql_fetch_array($ data)){ \t $ results [] = $ result; } return $ results; ( – Harinder

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說的那樣,回報打破了你的循環!

0

harinder,Function(mysql_fetch_array($data))返回一個數組。這意味着您的$result是一個數組,所以當你在查看頁面recevie的$result你必須使用foreach看看 這樣提取它:

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

因此你可以得到你所有的結果陣列。