PHP多维数组 - 如何正确分组

时间:2012-05-05 06:12:10

标签: php mysql multidimensional-array

如何正确分组数组:(最终结果)

Array
(
    [0] => Array
        (
            [Player] => CaLvErT
            [0] => Array
                (
                    [SnapTime] => 1330028992
                    [PlayCount] => 9
                )
        )
    [1] => Array
        (
            [Player] => CaLvErT
            [0] => Array
                (
                    [SnapTime] => 1330202828
                    [PlayCount] => 8
                )
        )
)

我的mySQL / PHP与我尝试过的一样:

        $iTestGrid = array();
        $ChartSQL = "SELECT player,snap,count(*) AS pCnt";
        $ChartSQL .= " FROM sc".$DBSvr;
        $ChartSQL .= " WHERE hex(alliance) IN (hex('Twitch'))";
        $ChartSQL .= " GROUP BY player,snap";
        $ChartSQL .= " ORDER BY player ASC,snap ASC";
        $FinalResult = $db-> query($ChartSQL);
        while ($FinalRow = $db-> fetch_assoc($FinalResult)){
           $iTestGrid[] = array(
            'Player' => $FinalRow['player'],
            array(
                'SnapTime' => (int)$FinalRow['snap'],
                'PlayCount' => (int)$FinalRow['pCnt']
            )
           );
        }

基本上想知道如何对具有相同名称的玩家进行分组。

提前感谢您的帮助! (请原谅我,因为我并不热衷于完全理解数组是如何工作的,所有日夜都通过书店而且仍然可以得到它的一部分,而不是很多)

2 个答案:

答案 0 :(得分:2)

如果我理解正确,你会想要这样的东西。 您可以使用播放器名称作为分组键,并将playcount / timestamp值推送到同一个数组中。

<?php 
    $iTestGrid = array();
    $ChartSQL = "SELECT player,snap,count(*) AS pCnt";
    $ChartSQL .= " FROM sc".$DBSvr;
    $ChartSQL .= " WHERE hex(alliance) IN (hex('Twitch'))";
    $ChartSQL .= " GROUP BY player,snap";
    $ChartSQL .= " ORDER BY player ASC,snap ASC";
    $FinalResult = $db-> query($ChartSQL);

    while ($FinalRow = $db-> fetch_assoc($FinalResult)){

        if(!isset($iTestGrid[$FinalRow['player']]))
            $iTestGrid[$FinalRow['player']] = array();

        $iTestGrid[$FinalRow['player']][] = 
        array(
            'SnapTime' => (int)$FinalRow['snap'],
            'PlayCount' => (int)$FinalRow['pCnt']
        );
    }

    var_dump($iTestGrid);

答案 1 :(得分:0)

也许你可以使用player name作为数组键并在该数组中插入其他数据:

$sorted = array();
foreach ( $result as $value ) {
    $sorted[ $value['Player'] ] = $value[ 0 ];
}
var_dump( $sorted );