简体   繁体   中英

need to fetch data from 2 tables in mysql

i have two tables filter_categories and filter tags

filter_categories
id | category 

filter_tags
id | filter_category_id | filter_tag

im writing following query to join these tables

"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"]."' 

im getting this result with 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

    )

)

But i need to fetch result like this

 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
    )
    )
   ) 

can someone help me out..how to do it? Thanks

First of all modify your query like this to get the id of category

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"].

then suppose your result are coming into $arrfilterALLDetails array then just use the for loop to modify the result as want above like below.

 $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);

Just play with this a littlebit you will get the result as you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM