数组来自数据库

时间:2012-04-26 08:35:56

标签: php mysql database arrays

我不热衷于如何从数据库中创建数组。试图避免学习那些,但显然现在需要它。

基本上我的数据库是由数百万行构成的。播放器名称和Snap(Unix TimeStamp)通常是“重复的”,但在这些行(城市,x,y等)中具有不同的数据。

理想情况下,尝试通过SELECT语句弄清楚如何制作数组:

输出,我希望是这样的: Name = Snap => (那天有多少个城市),Snap => (另一天有多少个城市)..等等..

这里的问题是,正确的数组“命令”(如果你调用它)是什么来拉取名称ONCE并使用基于快照的计数拉多次捕捉。

我的选择:

// SELECT count(*), player, snap
// FROM DB WHERE GROUP BY snap, player ORDER BY snap, player DESC
while ($row = fetch_assoc($Result) {
     // How you go about putting array here?
}

4 个答案:

答案 0 :(得分:2)

这样就可以了:

$Result = mysql_query("SELECT count(*) as count, player,
     snap FROM DB GROUP BY snap, player ORDER BY snap, player DESC");
while ($row = mysql_fetch_array($Result) {
  print_r( $row );
  echo "This is the count value -> " . $row['count'];
}

答案 1 :(得分:1)

我同意关于需要阅读更多基础知识的评论,但您可以执行以下操作,以创建多维数组:

<?php

$results = array();

$Result = 'SELECT count(*),player,snap FROM DB WHERE GROUP BY snap,player ORDER BY snap,player DESC';
while ($row = fetch_assoc($Result){
  if (!isset($results[$row['player']][$row['snap']]) {
    $results[$row['player']][$row['snap']] = 0;
  }
  $results[$row['player']][$row['snap']] += $row['count(*)']; 
}

?>

答案 2 :(得分:0)

首先尝试这些: -

  1. http://phpsense.com/2006/php-mysql/
  2. http://www.freewebmasterhelp.com/tutorials/phpmysql
  3. 您还需要有关SQL的基础知识。

答案 3 :(得分:0)

你可以尝试

$sql = "SELECT count(*) as count, player,
        snap FROM DB GROUP BY snap, player ORDER BY snap, player DESC";

/* Connect To Database */
$mysqli = new mysqli ( "localhost", "username", "password", "database" );

/* check connection */
if ($mysqli->connect_errno) {
    printf ( "Connect failed: %s\n", $mysqli->connect_error );
    exit ();
}

$result = $mysqli->query ( $sql );
$array = array();
if ($result) {
    while ( $row = $mysqli->fetch_assoc ( $result ) ) {
        $array[$row['player']] += $row['count'];
    }

    print_r($array); // Return array
}