我正在尝试实现类似 facebook 之类的小部件,它说:
You, Name1, Name2 and 20 other people like this
我获取了所有数据以显示此 HTML,但我似乎无法找到正确的算法来形成 HTML 字符串。
我的主要问题是我不知道何时放置and字符串或,(逗号)字符串。如果我只需要输入名称,它会起作用,但问题是You字符串总是必须放在第一位。
我将在此处粘贴我的代码以及针对某些特殊情况得到的输出(它是 PHP)。
$current_user = 0;
$html = "";
$count = count($result);
$key = 0;
foreach($result as $liked){
    if($key + 1 > $limit)
        break;
    if($liked->uid == $user->uid){
        $current_user = 1;
        continue;
    }
    $html .= "<a href='".$liked->href."'>".$liked->name."</a>";
    if($key < $count - 2)
        $html .= ", ";
    elseif($key == $count - 2 && $key + 1 != $limit)
        $html .= " and ";
    $key++;
}
if($current_user){
    $userHtml = "You";
    if($count > 2)
        $userHtml .= ", ";
    elseif($count > 1)
        $userHtml .= " and ";
    $html = $userHtml.$html;
}
$html = "♥ by ".$html;
if($count > $limit){
    $difference = $count - $limit;
    $html .= " and ".$difference." ".format_plural($difference,"other","others");
}
return $html;
在当前用户是最后一个喜欢这个的特殊情况下,它会显示:
♥ by You, admin, edu2004eu and
注意这个and词后面没有任何东西,因为You应该在它后面,但我把它放在了开头。有什么帮助吗?我只需要逻辑,而不是实际代码。