PHP MySQL - 显示子类别为count的父类别

时间:2018-03-05 07:09:02

标签: php mysql mysqli

我有以下两个MySQL表。

USERS TABLE

-----------------------------
user_id      category_id
-----------------------------
  1      |    101,115,138
  2      |    113,102,107
  3      |    156,101,133
  4      |    123,144,151
  5      |    122,114,116

类别表

-----------------------------
category_id    |    parent   
-----------------------------
    101        |      0      
    113        |     101
    114        |     101            
    115        |     101      
    116        |     101      
    102        |      0      
    123        |     102
    103        |      0      
    133        |     103
    138        |     103

依旧.....

我想只显示在USERS TABLE中找到的主要类别,以及它及其子类别所拥有的用户数量。

以下是我正在寻找的结果,

101(6) //This is 6 users because its 101,115,113,101,114,116 in USERS TABLE
102(2) //This is 2 users because its 102,122 in USERS TABLE
103(2) //This is 2 users because its 133,138 in USERS TABLE

依旧......

这就是我目前正在尝试的

$sqlg1='SELECT * FROM USERS_TABLE";';
        $resg1 = mysqli_query($connection, $sqlg1) or die("Error " . mysqli_error($connection));
        while($rowg1 = mysqli_fetch_array($resg1))
        {
            $countcats=0;
            $categoryids = $rowg1['category'];
            $categoryidsall = explode(',',$categoryids);                
            foreach($categoryidsall as $categoryid) 
            {                        
                $sqlg2='SELECT * FROM CATEGORIES_TABLE WHERE category_id="'.$categoryid.'";';
                $resg2 = mysqli_query($connection, $sqlg2) or die("Error " . mysqli_error($connection));                    
                while($rowg2 = mysqli_fetch_array($resg2))
                {
                    $chkparent = $rowg2['parent'];
                }

                if($chkparent!=0)
                {
                    $categoryid= $chkparent;
                    $countcats++;                    
                }
                else
                {
                    $countcats=1;
                }

                echo $categoryid.'('.$countcats.')';

            }

请帮助我如何获得所需的输出!

0 个答案:

没有答案