我正在建立一个排名系统,从数据库中获取数据(总数)并将它们从最高到最低排列。这是代码:
$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),我该怎么做?。
答案 0 :(得分:1)
Undgerman - 您必须连接到MySQL数据库:
http://us2.php.net/manual/en/function.mysql-connect.php
然后选择您的数据库:
http://us2.php.net/manual/en/function.mysql-select-db.php
然后执行MySQL查询:
http://us2.php.net/manual/en/function.mysql-query.php
然后获取结果:
http://us2.php.net/manual/en/function.mysql-fetch-assoc.php
实施例
<?php
mysql_connect( 'host', 'username', 'password' );
mysql_select_db( 'database' );
$result = mysql_query( 'SELECT * FROM `data`' );
$data = mysql_fetch_assoc( $result );
?>
意识到您可以在查询中对这些数据进行排序:
$result = mysql_query( 'SELECT * FROM `data` ORDER BY `totals`' );
答案 1 :(得分:1)
我现在已经完成了简单的排名系统,我想我应该分享我的代码。从pear获取db包,项目需要它。
<?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);
}