开发者

PHP combine values from loop

If I want to display the text as follows in example, how can it be done?

$tmp=mysql_query("SELECT ... FROM ....");
$total=mysql_num_rows($tmp);
$tekst1='Your total number of friends are: '.$total.'. Your friends are: ';
while($p=mysql_fetch_array($tmp)) {开发者_如何学编程
$tekst2=$p['friend'].", ";
}
$text_complete=$tekst1.$tekst2;
echo $text_complete;

$text_complete should look like: "Your total number of friends are: 3. Your friends are: John, Mike, Michael". But, using this code above I get "Your total number of friends are: 3. Your friends are: John,"

How can I combine both texts, the one obtained from the loop and the one which is fixed?


I think you shoul do like this:

       $tmp=mysql_query("SELECT ... FROM ....");
       $total=mysql_num_rows($tmp);
       $tekst1='Your total number of friends are: '.$total.'. Your friends are: ';
       $friends = array();
       while($p = mysql_fetch_array($tmp)) {
             $friends[] = $p['friend'];
       }
       $tekst2= implode(', ', $friends);
       $text_complete=$tekst1.$tekst2;
       echo $text_complete;

otherwise you overwrite the variable each time!

EDIT - i corrected the code to use implode as in Xaerxess answer. Previousli i just concatenated and use a substr to remove trailing comma and space


You can use:

$tekst2 .= $p['friend'].", ";

To add to the variable (rather than overwriting it. Then remove the trailing comma:

$text_complete=$tekst1. rtrim( $tekst2, "," );


$tekst2 = new Array();
while($p=mysql_fetch_array($tmp)) {
    $tekst2[] = $p['friend'];
}
$text_complete = $tekst1 . implode(', ',$tekst2);

But better would be to use GROUP_CONCAT in sql


$tmp=mysql_query("SELECT ... FROM ....");
$total=mysql_num_rows($tmp);
$tekst = '';
$tekst='Your total number of friends are: '.$total.'. Your friends are: ';
while($p=mysql_fetch_array($tmp)) {
$tekst.=$p['friend'].", ";
}
echo $tekst;


        $tmp=mysql_query("SELECT ... FROM ....");
        $total=mysql_num_rows($tmp);
        $tekst1='Your total number of friends are: '.$total.'. Your friends are: ';
        while($p=mysql_fetch_array($tmp)) 
           {
           $tekst1 .= $p['friend'].", "; // add friend names from MySQL result.
           }
        $tekst1 = substr($tekst2, 0, -2);//Remove comma.
        echo $tekst1; // Outputs the wanted string


Use PHP implode / join funciton, so there isn't any trailing comma at the end. In this case:

$fiends = array();
while($p = mysql_fetch_array($tmp)) {
     $friends[] = $p['friend'];
}
implode(', ', $friends);

EDIT: I basically doubled Billy Moon answer. What's more don't use mysql_* functions - they're deprecated not recommended - see comments below.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜