从SQL表创建多维数组

时间:2013-09-11 14:22:48

标签: php sql arrays

我有一张桌子'GOAL':

    ID   TYPE   KEY     VALUE
    --   ----   ---     -----
    1    RED    BASE    3
    2    BLUE   NAME    ALLOR
    3    RED    MAIN    _TTR
    4    GREEN  LOCAL   PIN,SEC,BALL,UNI
    5    BLUE   ALT     2DFFRST34@HH&FR#
    6    GREEN  DOMAIN  SITE.ORG,NSPL.EDU,ROAR.IN

我想在PHP中创建一个多维数组,它将产生这个数组:

    $GOAL = array (
        'RED'  => array    (
               'BASE' => 3,
               'MAIN' => '_TTR'
        ),
        'BLUE'   => array(
               'NAME' => 'ALLOR',
               'ALT' => '2DFFRST34@HH&FR#'
        ),
        'GREEN'   => array(
               'LOCAL' => 'PIN,SEC,BALL,UNI',
               'DOMAIN' => 'SITE.ORG,NSPL.EDU,ROAR.IN'
        )
    );

查询应该是什么?

1 个答案:

答案 0 :(得分:0)

这样的事情应该有效

  <?php 
        $query = mysql_query('SELECT * FROM GOAL');
        $goal = array();
        while($row = mysql_fetch_object($query)) {
            if(!isset($goal[$row->type])) {
                $goal[$row->type] = array();
            }
            $goal[$row->type][$row->key] = $row->value;
        }
    ?>