用If语句排序while

时间:2014-08-16 17:48:24

标签: php mysql while-loop

我有一个带有单词的mysql数据库。我用while语句打印所有单词。所以我想:

马铃薯 番茄 lettace

这一切都运行正常,但我想按长度对单词进行排序。我试过了:

if(strlen($go['words']) == 4 ){ echo "this are the 4 letter words:"; }

但这将在每4个字母单词之前打印句子。然而,我希望它只被打印一次作为所有4个字母单词的标题。当然,我也希望这样做5,6,7个字母。

我已经考虑过制作多个sql查询,但这对服务器来说太多了,无法处理很多访问者。

2 个答案:

答案 0 :(得分:1)

您可以使用这样的临时变量:

$tempLen = 0;
while(...)
{
    if(strlen($go['words']) == 1 && $tempLen < 1){ 
        echo "this are the 1 letter words:"; 
        $tempLen = 1;
    }
    ...
    if(strlen($go['words']) == 4 && $tempLen < 4){ 
        echo "this are the 4 letter words:"; 
        $tempLen = 4;
    }
    ...
}

答案 1 :(得分:0)

这是你想要的吗?

$words = array("fish", "mouse", "rabbit", "turtle", "duck");
sort($words);
$last_letter_count = 0;

foreach($words as $word)
{
    if ( strlen($word) != $last_letter_count )
    {
        $last_letter_count = strlen($word);
        echo "These are the $last_letter_count letter words:\n";
    }

    echo $word . "\n";
}

输出:

These are the 4 letter words:
duck
fish
These are the 5 letter words:
mouse
These are the 6 letter words:
rabbit
turtle