I have this code:

$sql=mysql_query("select distinct one.ime_kategorije AS ime_kat,count, two.kategorija_g AS kategorija_g
FROM (SELECT *, COUNT(DISTINCT kategorija_g) AS count FROM galerija_slik LEFT JOIN kategorija ON galerija_slik.id_kat=kategorija.id_kategorija GROUP BY id_kat) AS one
select *
from galerija_slik
group by kategorija_g) AS two
WHERE one.id_kat = two.id_kat;");
while ($row=mysql_fetch_array($sql)) {
    echo "<li>"; 
    echo $kategorija." "."(".$st.")";    
    echo "<ul>";
    echo "<li>".$kat."</li></ul>";
    echo "<li>";

But I have problem how to display this on my site.

I want to have like:

<li>Clanice (3)
<li>Ostalo (1)

I think that mysql part is good, but I don't know how to do this in php to display on this way.

With this code I get this:


That means threetimes Clanice and under this 1,2,3. But I like category Clanice only once and under this 1,2,3 like subcategories.

I forgot to write database tables:

g_id, link_slike, kategorija_g, ime_g, thumb_slike, datum, id_kat

id_kat is in relation with id_kategorija from kategorija table

id_kategorija, ime_kategorije