用很棒的字体替换图像

Replace images with font awesome

我正在尝试更改显示图像以供评论的代码。前面的代码有 5 个星星图像。第一张图片有一颗星,接下来有两颗,依此类推。每个图像的宽度都相同,因此对齐总是正确的。使用的代码是

    $p_stars = '<img src="images/stars_' . $rating . '.png">';

根据评分,以上结果会产生一串星星,例如

 ****
 *****
 *
 ***

我的想法是用超棒的字体图标替换图像,以便更容易控制颜色,如果需要更改颜色或星星数量,则需要更少的维护。我这样做了,它工作正常,但它需要的代码量远远超过图像。所以我的问题是:

这是图标方法的代码:

    <style>
    .stars {color:#FB9802;}
    .stars-hide {color:#fff;}
    </style>

    $p_stars  = '';
    $p = 0;
    while ($p < 5) {
        for ($x = 0; $x < $rating; ++$x) {
            $p_stars .= '<i class="fas fa-star stars"></i>';
            $p++;
        }
        if ($p == 5) break;

        for ($x = $p; $x < 5; ++$x) {
            $p_stars .= '<i class="fas fa-star stars-hide"></i>';
            $p++;
        }
    }

Should I stick with the images?

没有人会为您回答这个问题。你必须自己决定。坚持适合你、你的团队和你的客户的任何东西。编程中最重要的是沟通(至少我是这么认为的)。

我将把 fyrye 写在评论中的内容包括在内,这是一个很好的观点:

From a standardization and optimization approach, using Font Awesome, if used extensively... is more beneficial than a series of different images... However if it is only used for the stars, it is a very large asset to download for one single use.


Is there a better way to code for the icon method?

... the amount of code it takes is far more than with the images...

你应该更聪明地工作,而不是更努力:)

如果您研究所有可用的 PHP 数组函数,您会遇到 array_fill

现在,与 array_merge 一起,我们可以创建一段非常优雅且易于维护的代码,它在您的提交中看起来比您已经拥有的要好得多:)

看看这个:

$imageShow = '<i class="fas fa-star stars"></i>';
$imageHide = '<i class="fas fa-star stars-hide"></i>';

$rating = 3;

$stars = array_merge(
    array_fill(0, $rating, $imageShow),
    array_fill($rating, 5-$rating, $imageHide)
    );
    
var_dump($stars);

这就是 var_dump 的结果:

array(5) {
  [0]=>
  string(33) "<i class="fas fa-star stars"></i>"
  [1]=>
  string(33) "<i class="fas fa-star stars"></i>"
  [2]=>
  string(33) "<i class="fas fa-star stars"></i>"
  [3]=>
  string(38) "<i class="fas fa-star stars-hide"></i>"
  [4]=>
  string(38) "<i class="fas fa-star stars-hide"></i>"
}

看到了吗?我将 $rating 设置为 3,结果数组有 3 个星星图像和 2 个隐藏星星图像。

现在,您只需要一个 implode 调用即可将所有元素连接在一起。我相信,您的生产代码最终会像这样:

$imageShow = '<i class="fas fa-star stars"></i>';
$imageHide = '<i class="fas fa-star stars-hide"></i>';

$stars = array_merge(
    array_fill(0, $rating, $imageShow),
    array_fill($rating, 5-$rating, $imageHide)
    );

$p_stars = implode("", $stars);