如何以三维数组格式运行查询和获取项目

时间:2014-02-21 09:19:27

标签: php mysql

我一直试图从各州的地方议会和地方议会获得城镇。我能够从州获得地方议会,但从地方议会获得城镇是一个问题。它一直告诉我非法抵消。这是我的代码:

$querys = "select id,title from link where (parent is null or parent=0) and title is not null and category='state' and type='1' order by title";
$results = mysql_query($querys,$link) or die(mysql_error());
$counts = 0;
while($rows= mysql_fetch_array($results,MYSQL_ASSOC))
{
    $state_id[] = $rows["id"];//echo $state_id[$counts]."<br>";
    $state[] = $rows["title"];
    $querylg = "select id,title from link where title is not null and category='lga' and type='1' and parent={$rows['id']} and parent is not null order by title";
    $resultlg = mysql_query($querylg,$link) or die(mysql_error());
    $countlg[$counts] = 0;
    while($rowk=mysql_fetch_array($resultlg,MYSQL_ASSOC))
    {
        $lg_id[$counts][] = $rowk["id"];//echo $lg_id[$counts][$countlg]."<br>";
        $lg_name[$counts][] = $rowk["title"];
        $queryt = "select id,title from link where title is not null and category='town' and type='1' and parent={$rowk['id']} and parent is not null order by title";
        $resultt=mysql_query($queryt,$link) or die(mysql_error());
        $counttw[$countlg][$counts] = 0;
        while($row=mysql_fetch_array($resultt,MYSQL_ASSOC))
        {
            $tw_id[$counts][$countlg][] = $row["id"];
            $tw_name[$counts][$countlg][] = $row["title"];
            $counttw[$countlg][$counts]++;  
        }
        $countlg[$counts]++;
    }
    $counts++;
}

1 个答案:

答案 0 :(得分:0)

我不太确定你的代码究竟是什么(即有多少计数等等,只是为了获得你的数组,以及实际需要多少)。你能把你想要的实际输出吗?

我很想根据一个连接的查询重写它: -

SELECT a.id AS state_id, a.title AS state_title, b.id AS lg_id, b.title AS lg_title, c.id AS town_id, c.title AS town_title
FROM link a
LEFT OUTER JOIN link b ON a.id = b.parent AND b.title IS NOT NULL AND b.category='lga' AND b.type='1'
LEFT OUTER JOIN link c ON b.id = c.parent AND b.title IS NOT NULL AND b.category='town' AND b.type='1'
WHERE (a.parent IS NULL OR a.parent=0) AND a.title IS NOT NULL AND a.category='state' AND a.type='1' 
ORDER BY a.title, b.title, c.title