使用数据库中的数据构建排名系统 [英] building ranking system with data from the database
本文介绍了使用数据库中的数据构建排名系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在构建一个排名系统,该系统从数据库中获取数据(总计)并将它们从最高到最低进行排名.以下是代码:
I am building a ranking system that takes data(totals) from the database and ranks them from the highest to the lowest.Here is the code:
$data = array(
'A'=>19,'B'=>18,'C'=>17,'D'=>17,'E'=>16,'F'=>15
);
//Populate the arrays with data from mysql
/*
--
-- Table structure for table `data`
--
CREATE TABLE IF NOT EXISTS `data` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`totals` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=501 ;
--
-- Dumping data for table `data`
--
INSERT INTO `data` (`id`, `totals`) VALUES
(1, 468),
(2, 450),
(3, 400),
(4, 419),
(5, 400),
(6, 400),
(7, 500),
(8, 489),
(9, 412),
(10, 385);
*/
$rank = 0;
$lastScore = PHP_INT_MAX;
foreach( $data as $name=>$score ) {
if ( $lastScore !== $score ) {
$lastScore = $score;
$rank += 1;
}
printf("%s %d (%d)\n", $name, $score, $rank);
}
我想要一种用存储在数据库中的值填充变量($ data)的方法,该怎么办?.
I want a way to populate the variable($data) with the values stored in the database,how can i do that?.
推荐答案
我现在已经完成了简单的排名系统的构建,我认为我应该共享我的代码.从pear获取db软件包,该项目需要它.
I have now finished building the simple ranking system and i thought i should share my code.Grab the db package from pear,the project needs it.
<?php
require_once 'DB.php';
$dsn = array(
'phptype' => 'mysql',
'username' => 'root',
'password' => '',
'hostspec' => 'localhost',
'database' => 'rm-db',
);
$options = array(
'debug' => 2,
'portability' => DB_PORTABILITY_ALL,
);
$db =& DB::connect($dsn, $options);
if (PEAR::isError($db)) {
die($db->getMessage());
}
$data =& $db->getCol('SELECT totals FROM data order by totals desc');
if (PEAR::isError($data)) {
die($data->getMessage());
}
//print_r($data);
//Populate the arrays with data from mysql and arrange in descending order.
//SELECT * FROM data order by totals desc
/*
--
-- Table structure for table `data`
--
CREATE TABLE IF NOT EXISTS `data` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`totals` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=501 ;
--
-- Dumping data for table `data`
--
INSERT INTO `data` (`id`, `totals`) VALUES
(1, 468),
(2, 450),
(3, 400),
(4, 419),
(5, 400),
(6, 400),
(7, 500),
(8, 489),
(9, 412),
(10, 385);
*/
$rank = 0;
$lastScore = PHP_INT_MAX;
foreach( $data as $name=>$score ) {
if ( $lastScore !== $score ) {
$lastScore = $score;
$rank += 1;
}
printf("%s %d (%d)\n", $name, $score, $rank);
}
这篇关于使用数据库中的数据构建排名系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文