Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 为该国展示世界排名前5%和前10%的奖杯[按百分比排名系统]_Php_Mysql_Pdo_Ranking - Fatal编程技术网

Php 为该国展示世界排名前5%和前10%的奖杯[按百分比排名系统]

Php 为该国展示世界排名前5%和前10%的奖杯[按百分比排名系统],php,mysql,pdo,ranking,Php,Mysql,Pdo,Ranking,我正在做一个php游戏,所以我有一个“国家/地区/发展/地区”表格,里面有奖杯,应该出现在用户的国家/地区页面上。每个奖杯从“值”0开始,然后再向上。值越大,排名越高。我已随表格附上一张图片,如下所示: 在用户国家/地区页面上应显示两行: -第1行显示“价值”字段中世界排名前5%的国家对应的奖杯。 -第二行显示了与“价值”领域排名前10%的国家相对应的奖杯 排名应根据“价值”与所有国家进行比较,并显示与该国家相对应的奖杯线。它还应该在链接标题中有相应的排名,如“最有效的经济体:3420” 贝娄

我正在做一个php游戏,所以我有一个“国家/地区/发展/地区”表格,里面有奖杯,应该出现在用户的国家/地区页面上。每个奖杯从“值”0开始,然后再向上。值越大,排名越高。我已随表格附上一张图片,如下所示:

在用户国家/地区页面上应显示两行: -第1行显示“价值”字段中世界排名前5%的国家对应的奖杯。 -第二行显示了与“价值”领域排名前10%的国家相对应的奖杯

排名应根据“价值”与所有国家进行比较,并显示与该国家相对应的奖杯线。它还应该在链接标题中有相应的排名,如“最有效的经济体:3420”

贝娄是我到目前为止的代码,它显示了奖杯,但它显示了所有,所以我不知道如何让他们显示百分比排名


这是完整的代码,包括排名。您可以添加任意数量的顶级类型

  • 不要在id列中使用id=0
  • 在表格中不放置图标html。只在图标列中输入图标名称,如“hand-peace-o”
  • 有关正确准备的语句+验证+异常处理的信息,请参阅(如果要使用类,请参阅编辑部分)
  • 我只使用了
    图标
    列中的图标名称
  • 您应该在
    catch
    块中使用我的建议。因为异常通常是一种错误类型,在此之后,您不想继续任何程序步骤,而只想在屏幕上显示错误消息并退出
  • 尽量避免在任何编程语言的代码中使用
    while
    语句。除了可能在那里,他们在哪里。。。不可避免的例如,如果它们有很好的文档记录,比如PHP文档网站上的不同数据访问功能,并且确实需要,那么就使用它们。但要小心,因为它们可能会导致无限循环,从而使服务器完全过载
  • 将PHP数据访问部分与HTML部分分开。如果需要数据,请在PHP数组和PHP页面的上半部分中获取所有数据。在PHP页面的HTML部分,只需迭代这些数组。因此,简而言之,不要将PHP数据访问代码与HTML代码混用。比如:PHP页面的HTML部分中没有
    fetch()
祝你好运

PHP代码:
你想要什么还不太清楚。您的代码是错误的(
fetch()
function获取一行!),因此没有多大用处。你的解释,例如“应该…”和“排名应该…”,也有点令人困惑。不清楚您是否需要一个数字(一个
s之和)或一个
名称
/
对的列表,等等。因此,请进行一次“编辑”,并给出更清楚的解释,并准确地显示输出应该是什么样子(不是php,而是最终结果,例如用户应该在屏幕上看到什么)。进行了编辑。如果清楚,请告诉我。谢谢。第一个问题:“前5%”到底是什么意思?前5%的国家或前5%的地区?按地区价值计算的前5%。例如,有50个国家各自拥有自己的民权面积价值。比方说,对于id为1的国家,看看与其他民权国家相比,她的民权领域是否在前5%。如果它位于前5%,则在第一行显示它。如果它位于前10%,则将其显示在第二行。因此,让我们看看您的表格,并说以下内容:
民权
所有国家的
s的总和为102。那么95%的限制(关于
列)是:0.95*102=96.9。因此,当一个国家的
民权
区域的
>=96.9时,该区域应显示在第一行。是吗?我很困惑:假设国家1的“公民权利”被显示(例如在顶部)。排名结果(一个数字)应该是“民权”在所有国家的所有“民权”列表中所占的位置(例如排名位置)(与排名靠前的事实无关)?如果是的话,那么理论上,“民权”在所有3项排名中的排名都是相同的。是吗?在所有国家的所有“公民权利”列表中,“公民权利”占据的位置。感谢您的解决方案,它工作得很好。但是,如果顶部没有奖杯,我如何隐藏顶部5%、10%等文本?屏幕截图显示它是否仅在前80%中:查看所有空文本:前5%前10%前20%。在HTML第一部分中,添加了检查:“如果当前顶部的区域列表不为空,则显示区域。”——
if($areas){}
直到现在才注意到。我认为计算有问题。我有政治自由,数据库中的值为1000,但它仍然没有显示在前5%中,它显示在其他前5%中。屏幕:
<?php
// Get all rows from country_development_areas table
try {
    // Read from HTTP POST.
    $country = 1;

    /*
     * Array containing the top types (top 5%, top 10%, top 20%, etc) as keys and
     * the areas lists for each top as values.
     */
    $tops = array(
        5 => array(),
        10 => array(),
        20 => array(),
        80 => array(),
    );

    // Create a PDO instance as db connection to a MySQL db.
    $db = new PDO(
            'mysql:host=localhost;port=3306;dbname=yourDB'
            , 'yourUser'
            , 'yourPass'
    );

    // Assign the driver options to the db connection.
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
    $db->setAttribute(PDO::ATTR_PERSISTENT, TRUE);

    // Iterate through tops and fetch the top areas.
    foreach ($tops as $top => $results) {
        // The sql statement - it will be prepared.
        $sql = 'SELECT 
                    cda.*,
                    (
                        SELECT (COUNT(DISTINCT value) + 1)
                        FROM country_development_areas
                        WHERE 
                            name = cda.name
                            AND value > cda.value
                    ) AS rankPositionInTheWorld,
                    (
                        SELECT (COUNT(DISTINCT value) + 1)
                        FROM country_development_areas
                        WHERE 
                            name = cda.name 
                            AND value > cda.value 
                            AND value >= :topDownLimit1 * (
                                SELECT SUM(IFNULL(value, 0)) 
                                FROM country_development_areas 
                                WHERE name = cda.name
                            )
                    ) AS rankPositionInTop 
                FROM country_development_areas AS cda
                WHERE
                    cda.country = :country AND
                    cda.value >= :topDownLimit2 * (
                        SELECT SUM(IFNULL(value, 0)) 
                        FROM country_development_areas 
                        WHERE name = cda.name
                    )';

        // The input parameters list for the prepared sql statement.
        $bindings = array(
            ':country' => $country,
            ':topDownLimit1' => 1 - $top / 100,
            ':topDownLimit2' => 1 - $top / 100,
        );

        // Prepare and validate the sql statement.
        $stmt = $db->prepare($sql);

        if (!$stmt) {
            throw new UnexpectedValueException('The sql statement could not be prepared!');
        }

        // Bind the input parameters to the prepared statement.
        foreach ($bindings as $key => $value) {
            // Get the name of the input parameter by its key in the bindings array.
            $inputParameterName = is_int($key) ? ($key + 1) : (':' . ltrim($key, ':'));

            // Get the PDO::PARAM_* constant, e.g the data type of the input parameter, by its value.
            if (is_int($value)) {
                $inputParameterDataType = PDO::PARAM_INT;
            } elseif (is_bool($value)) {
                $inputParameterDataType = PDO::PARAM_BOOL;
            } else {
                $inputParameterDataType = PDO::PARAM_STR;
            }

            // Bind and validate the binding of the input parameter.
            $bound = $stmt->bindValue($inputParameterName, $value, $inputParameterDataType);

            if (!$bound) {
                throw new UnexpectedValueException('An input parameter could not be bound!');
            }
        }

        // Execute the prepared statement.
        $executed = $stmt->execute();

        if (!$executed) {
            throw new UnexpectedValueException('The prepared statement could not be executed!');
        }

        /// Fetch and validate the areas list.
        $topAreas = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if ($topAreas === FALSE) {
            throw new UnexpectedValueException('Fetching data failed!');
        }

        $tops[$top] = $topAreas;
    }

    // Close connecion.
    $connection = NULL;
} catch (PDOException $e) {
    $error[] = $e->getMessage();

    // My recommendation:
    // echo $e->getMessage();
    // $logger->log($e);
    // exit();
} catch (Exception $e) {
    $error[] = $e->getMessage();

    // My recommendation:
    // echo $e->getMessage();
    // $logger->log($e);
    // exit();
}
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Trophies test</title>

        <!-- ======================================= -->
        <!-- CSS resources -->
        <!-- ======================================= -->

        <!-- Font-Awesome -->
        <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css" rel="stylesheet" />

        <!-- Bootstrap -->
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" rel="stylesheet" />

        <!-- ======================================= -->
        <!-- JS resources -->
        <!-- ======================================= -->

        <!-- jQuery -->
        <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>

        <!-- Bootstrap -->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript"></script>

        <style type="text/css">
            body {
                padding: 30px 15px;
            }

            .legend {
                margin-bottom: 30px;
                max-width: 30%;
            }

            .legend-title {
                background-color: #eee;
            }

            .trophy-cabinet-title {
                margin-bottom: 10px;
            }

            .trophy-cabinet {
                margin-bottom: 20px;
            }

            .top-area {
                padding: 10px;
                border: 1px solid #ccc;
                border-radius: 4px;
                display: inline-block;
            }
        </style>
    </head>
    <body>

        <div class="list-group legend">
            <div class="list-group-item legend-title">
                Legend
            </div>
            <div class="list-group-item">
                WP: Rank position in the world
            </div>
            <div class="list-group-item">
                TP: Rank position in the top
            </div>
        </div>

        <?php
        // Just for testing, to see the areas list of all tops on screen.
        // echo '<pre>' . print_r($tops, TRUE) . '</pre>';
        ?>

        <?php
        foreach ($tops as $top => $areas) {
            /*
             * If the list of areas for the current top 
             * is not empty, then display the areas.
             */
            if ($areas) {
                ?>
                <div class="trophy-cabinet-title">
                    Trophy cabinet for top <?php echo $top; ?>%.
                </div>
                <div id="trophyCabinet<?php echo $top; ?>Percent" class="trophy-cabinet">
                    <?php
                    foreach ($areas as $area) {
                        $areaId = $area['id'];
                        $areaIcon = $area['icon'];
                        $areaTitle = $area['title'];
                        $areaRankPositionInTheWorld = $area['rankPositionInTheWorld'];
                        $areaRankPositionInTop = $area['rankPositionInTop'];
                        ?>
                        <a class="top-area top<?php echo $top; ?>percent" href="/nation=united_states_of_america/detail=trend?censusid=<?php echo $areaId; ?>" title="<?php echo $areaTitle; ?>: <?php echo $areaRankPositionInTheWorld; ?>">
                            <div class="trophy">
                                <i class="fa fa-<?php echo $areaIcon; ?>"></i> WP <?php echo $areaRankPositionInTheWorld; ?> &bullet; TP <?php echo $areaRankPositionInTop; ?>
                            </div>
                        </a>
                        <?php
                    }
                    ?>
                </div>
                <?php
            }
        }
        ?>

    </body>
</html>
========================================
Create table syntax
========================================

DROP TABLE IF EXISTS `country_development_areas`;

CREATE TABLE `country_development_areas` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `country` int(11) DEFAULT NULL,
  `name` varchar(100) DEFAULT NULL,
  `value` int(11) DEFAULT NULL,
  `icon` varchar(100) DEFAULT NULL,
  `title` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

========================================
Insert values syntax
========================================

INSERT INTO `country_development_areas` (`id`, `country`, `name`, `value`, `icon`, `title`)
VALUES
    (0,1,'Civil Rights',2,'hand-peace-o','Most Free People'),
    (1,1,'Economy',10,'area-chart','Most Efficient Economies'),
    (2,1,'Political Freedom',8,'handshake-o','Most Political Freedom'),
    (3,1,'Population',1,'users','Largest Population'),
    (4,2,'Civil Rights',100,'hand-peace-o','Most Free People'),
    (5,2,'Political Freedom',2,'handshake-o','Most Political Freedom');