0

我有一张桌子,基本上是这样的

------------------
id | name  | type
------------------
1  | name1 | type1
2  | name2 | type2
3  | name3 | type3 
------------------

我想查询它并将其显示为类似

type1
 - name1
 - and so on...
type2
 - name2
 - and so on...    
type3
 - name 3
 - and so on...

我还希望将其显示为 JSON 文件,类似于

   [
    {
        "type1": {
            "name": "name1"
        },
        "type2": {
            "name": "name2"
        },
        "type3": {
            "name": "name3"
        }
    }
]

那么,我可以知道最好的方法吗?使用循环查询类型,然后选择类别并按类型显示?

编辑:在互联网上搜索高低后。我发现了这个:http ://www.tommylacroix.com/2008/09/10/php-design-pattern-building-a-tree/

因此,根据我的需要制定了此代码。不确定它是否有效:

<?php
$query = "SELECT * FROM TABLE";
$list = array();
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
    if(!$list[$row['type']])
    {
        $list[$row['type']] = array();
    }
    array_push($list[$location['type']],&$row['name']) ;
}
?>
4

1 回答 1

4

Try This.... also see the result output below

SELECT id,CONCAT_WS(',',type,name) as result FROM table GROUP BY id

<?php
$sql= mysql_query("SELECT id,CONCAT_WS(',',type,name) as result FROM table GROUP BY id");
$data = array();
$i=0;
while($row = mysql_fetch_array($sql)){

    $ex_res = explode(",",$row['result']);
    $data[$ex_res[0]]['name'] = $ex_res[1];  
    $i++;
}

$a = json_encode($data);
print_r($a);
?>

Result Output

{"type1":{"name":"name1"},"type2":{"name":"name2"},"type3":{"name":"name3"}}
于 2012-06-03T06:56:21.923 回答