根据用户数量,在字符串中用“,”或“和”分隔用户名

时间:2014-01-04 16:08:57

标签: php string loops foreach while-loop

$playernothing = 0;
$sortdrawmax = max($p1count,$player2count,$player3count,$player4count,$player5count,$player6count,$player7count);
$sortdraww = mysql_query("SELECT username,count FROM blackjackmultijoin WHERE gameid = '$gameid' AND count = '$sortdrawmax'");
while($sortdraw = mysql_fetch_array($sortdraww)){
$playernothing++;
$playersname.$playernothing = $sortdraw['username'];
}

if($sortdrawmax < 1){ 
   $drawoutcome = "All users <b>busted</b> and the game will restart in <b>$gamedrawleft</b> seconds..."; 
}
elseif($playernothing == 2){ 
   $drawoutcome = "$playersname1 and $playersname2 drew with <b>$sortdrawmax</b>! Game will restart in <b>$gamedrawleft</b> seconds..."; 
 }
elseif($playernothing == 3){ 
   $drawoutcome = "$playersname1, $playersname2 and $playersname3 drew with <b>$sortdrawmax</b>! Game will restart in <b>$gamedrawleft</b> seconds..."; 
}

我在多人Blackjack脚本的一部分中有上述代码 我的意图是一个代码,它将完成上面的$drawoutcome,这样对于每个用户中抽奖金额最高的用户都会用逗号分隔,其姓氏在“和”之后。

任何人都可以帮助正确的方法吗?

2 个答案:

答案 0 :(得分:0)

首先,将名称放入数组中,而不是单个变量。获得完整的播放器列表后,使用array_pop从阵列中删除最后一个播放器(并将其设置为变量)。最后,使用implode加入列表的其余部分,最后使用字符串concat。

假设你已经拥有一系列玩家($ player_list):

$last_player = array_pop($player_list);
$draw_outcome = implode(', ', $player_list) . ' and ' . $last_player;

此代码需要处理少于2名玩家的特殊情况,否则应该是好的。

答案 1 :(得分:0)

$playernothing = 0;
$sortdrawmax = max($p1count,$player2count,$player3count,$player4count,$player5count,$player6count,$player7count);
$sortdraww = mysql_query("SELECT username,count FROM blackjackmultijoin WHERE gameid = '$gameid' AND count = '$sortdrawmax'");
while($sortdraw = mysql_fetch_array($sortdraww))
{
    $playernothing++;
    $arr[] = $playersname.$playernothing = $sortdraw['username'];
}
if(count($arr) > 1)
{
    $last = $arr[count($arr)-1];
    unset($arr[count($arr)-1]);
    $usernames = implode(",", $arr)." and {$last}";
}
else
    $usernames = implode("", $arr);
if($sortdrawmax < 1)
{ 
   $drawoutcome = "All users <b>busted</b> and the game will restart in <b>$gamedrawleft</b> seconds..."; 
}
elseif($playernothing == 2)
{ 
   $drawoutcome = "$usernames drew with <b>$sortdrawmax</b>! Game will restart in <b>$gamedrawleft</b> seconds..."; 
}
elseif($playernothing == 3)
{ 
   $drawoutcome = "$usernames drew with <b>$sortdrawmax</b>! Game will restart in <b>$gamedrawleft</b> seconds..."; 
}