PHP making HTML menu with Recursive Function

I have categories table in MySQL Database. It looks like this; categories Table Image

I have a function for make a Recursive Function for make HTML Menu. But, I'm stuck for last 3-4 hours. This is my code in Codeigniter Model;

public function deneme($parent_id = 0, $sub_mark = 0) {
    $this->db->select('*');
    $this->db->from('categories');
    $this->db->where('parent_id = ' . $parent_id);
    $this->db->order_by('id', 'ASC');
    $query = $this->db->get();
    if($query->num_rows() > 0) {
        foreach($query->result_array() as $row) {
            echo '
            <li class="active">
                <a href="index.html">' . $row['name'] . '</a>
            </li>
            ';
            $sub_mark++;
            $this->deneme($row['id'], $sub_mark, $str);
        }
    }
}

So, it only can make this;

<li class="active">
    <a href="index.html">Anasayfa</a>
</li>
<li class="active">
    <a href="index.html">Uygulamalar</a>
</li>
<li class="active">
    <a href="index.html">Cilt Bakımı</a>
</li>
<li class="active">
    <a href="index.html">Medikal Cilt Bakımı</a>
</li>
<li class="active">
    <a href="index.html">Innofacial İle Bakım</a>
</li>
.
.
.

But, I want to do this like;

<li class="active">
    <a href="index.html">Anasayfa</a>
</li>
<li class="active">
    <a href="index.html">Uygulamalar</a>
    <ul>
        <li>
            <a href="index.html">Cilt Bakımı</a>
                <ul>
                    <li>
                        <a href="index.html">Medikal Cilt Bakımı</a>
                    </li>
                    <li>
                        <a href="index.html">Innofacial Ile Bakım</a>
                    </li>
                    <li>
                        <a href="index.html">Jetpeel Ile Bakım</a>
                    </li>
                </ul>
        </li>
    </ul>
</li>
.
.
.

How can I do this? Thanks!

Upvotes: 0

Views: 452

Answers (1)

Mohammad C
Mohammad C

Reputation: 1341

You are missing the ul tags to make your list nested. Also i added an if statement to make sure only the top level lists have active class.

if($query->num_rows() > 0) {
    echo '<ul>';
    foreach($query->result_array() as $row) {
        if ($parent_id == 0) {
            echo '<li class="active">';
        } else {
            echo '<li>';
        }
        echo '<a href="index.html">' . $row['name'] . '</a> </li> '; 
        $sub_mark++;
        $this->deneme($row['id'], $sub_mark, $str);
    }
    echo '</ul>';
}

Upvotes: 1

Related Questions