0

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!

1 Answer 1

1

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>';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow! Very good! How can I return a string when the latest call to function, do you have any idea about this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.