需要从mysql中的2个表中获取数据

时间:2015-11-09 12:10:23

标签: php mysql mysqli

我有两个表filter_categories和过滤标签

filter_categories
id | category 

filter_tags
id | filter_category_id | filter_tag

我正在编写以下查询以加入这些表

"select filter_categories.filter_category,
filter_tags.filter_tag from filter_categories JOIN filter_tags ON 
(filter_tags.filter_category_id=filter_categories.id) where   
 filter_categories.filter_id='".$_GET["id"]."' 

我用php print_r()

获得这个结果
Array
(
[0] => Array
    (

        [filter_category] => abcty
               [filter_tag] => sdfds

    )

[1] => Array
    (

        [filter_category] => abcty

        [filter_tag] => dgdfg

    )

[2] => Array
    (

        [filter_category] => abcty

        [filter_tag] => gdgdf

    )

[3] => Array
    (

        [filter_category] => abcty

        [filter_tag] => dgdfgf

    )

[4] => Array
    (


        [filter_category] => abcty
        [filter_tag] => dsfs

    )

但我需要像这样获取结果

 Array
(
[0] => Array
    (

        [filter_category] => abcty
        [filter_tag] => array(
        [filter_tag] => dgdfg
        [filter_tag] => dgdfgf
        [filter_tag] => dsfs
)
)
)

[1] => Array
    (

        [filter_category] => efg
       [filter_tag] => array(

  [filter_tag] => et
[filter_tag] => yu
 [filter_tag] => op
    )
    )
   ) 

有人可以帮助我......怎么做? 感谢

1 个答案:

答案 0 :(得分:0)

首先修改你的查询,得到类别的id

select filter_categories.id,filter_categories.filter_category,
filter_tags.filter_tag from filter_categories JOIN filter_tags ON 
(filter_tags.filter_category_id=filter_categories.id) where   
 filter_categories.filter_id='".$_GET["id"].

然后假设你的结果进入$arrfilterALLDetails数组然后只需使用for循环来修改结果,如下所示。

 $arrfilterDetails = array();
 foreach ($arrfilterALLDetails as $key => $value) {
          $arrfilterDetails[$value['id']]['filter_category'] = $value['filter_category'];
          $arrfilterDetails[$value['id']][$value['filter_tag']] = $value['filter_tag'];
        }
print_r($arrfilterDetails);

只要玩这个小小的比特,你就可以得到你想要的结果。