【问题标题】:How to display stars (1 to 5) from the value present in database如何根据数据库中存在的值显示星号(1 到 5)
【发布时间】:2020-02-15 17:52:46
【问题描述】:

我开发了一个显示用户成就详细信息的页面。我有一个保存用户级别的表。

用户(id、用户名、密码、sum_score、级别)

基于级别中存在的值(即从 0 到 5),我想在用户页面中显示星星。

我试过类似的东西:

$stars = "";
$s = 1;
while ($s<=$lvl['level']) {
    $stars.="&#9733;";
    $s++;
}

echo "$stars";

以上代码根据级别生成星号。(即,如果级别为 1,则在页面上显示一颗星)。但我想显示 5 颗星并根据表中的级别填充星星。谁能帮帮我。

【问题讨论】:

  • 欢迎。使用for loop ?
  • 我没有看到您的代码有任何问题。如果$lvl['level'] 正在从数据库中获取正确的信息(即 5),它应该可以正常工作。你能告诉我们$lvl['level']的回报吗?
  • @Joska 无论如何你都想显示 5 颗星,例如只填充其中的一颗?
  • @LucasArbex 该代码可以显示星星,但我想显示所有 5 颗星星并根据级别仅填充星星
  • @angel.bonev 是的,如果是一级,我只需要填一颗星

标签: php html css


【解决方案1】:

在这种情况下,您可以使用简单的for 循环而不是使用while。

假设 $lvl['level'] 正确获取数据库的数据(即 5),您可以循环直到 5 将其与 $lvl['level'] 值进行比较,并根据 if 语句的结果显示星号。像这样:

$stars = "";

for ($i = 1; $i <= 5; $i++) { 
    $i <= $lvl['level'] ? $stars .= "&#9733;" : $stars .= "&#9734;";
}

echo $stars;

【讨论】:

    【解决方案2】:

    str_repeat 是一种选择。

    // stub for your record
    $lvl = [
      'level' => 4
    ];
    
    // render
    $maxStars = 5;
    $stars = (int)$lvl['level'];
    $output = 
      str_repeat('&#9733;', $stars) . 
      str_repeat('&#9734;', $maxStars - $stars) .
      ' stars';
    
    echo $output;
    

    输出:https://3v4l.org/UFprQ

    【讨论】:

      【解决方案3】:

      如果你添加一些类和持有者,并在循环中添加一个 if 语句

      <?php
      $lvl = ["id" => 1, "level" => 4];
      $stars = "";
      for ($i = 1; $i < 6; $i++) {
          $stars .= '<span' . (($i <= $lvl["level"]) ? ' class="fill"' : '') . '>';            
          $stars .='&#9733;</span>';
      }
      echo '<div class="star"><div class="rating">' . $stars . '</div></div>';
      

      这里是sn-p,HTML代码是PHP的输出:

      .star {
        width: 200px;
        position: relative;
        color: #bdbdbd;
      }
      
      .rating span {
        font-size: 30px;
        margin-left: -4px;
        white-space: nowrap;
        overflow: hidden;
      }
      
      .rating span:before {
        content: "\2605";
        position: absolute;
        color: gray;
      }
      
      .rating span.fill:before {
        content: "\2605";
        position: absolute;
        color: gold;
      }
      <!-- this will be the output generated from php code used above !-->
      <div class="star">
        <div class="rating"><span class="fill">★</span><span class="fill">★</span><span class="fill">★</span><span>★</span><span>★</span></div>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多