1

I've searched about how to make category tree and always found with using recursive. But I want to know how to make a list of category tree without using recursive, Is it possible?

Data:

$arrItems = array(
    array('id' => 1, 'parent_id' => 0),
    array('id' => 2, 'parent_id' => 1),
    array('id' => 3,  'parent_id' => 2),
    ...
);

Output:

<ul>
    <li> 1 
        <ul>
            <li> 3 </li>
            <li> 5 
                <ul>
                    <li> 7 </li>
                    ...
                </ul>
            </li>
        </ul>
    </li>
    <li> 2 
        ...
    </li>
</ul>

Thanks in advance.

2
  • Can you add your recursive solution ? Commented Nov 29, 2018 at 16:02
  • Yes it is possible.. You can create your own stack and achieve that. Commented Nov 29, 2018 at 20:24

1 Answer 1

2

You can do it by converting the parent relationships to child relationships. For that you need one iteration. You could use this function for it:

function toTree($arrItems) {
    $children = [];
    foreach($arrItems as $item) $children[$item["parent_id"]][] = $item["id"];
    return $children;
}

Then, once you have that data structure, you can convert it to your HTML structure with the following function:

function toHTML(&$children, $parent=0, $indent="") {
    if (!isset($children[$parent])) return ""; 
    return "$indent<ul>\n" . implode("", array_map(function($id) use ($children, $indent) {
        return "$indent  <li>$id\n" . toHTML($children, $id, "$indent    ") . "$indent  </li>\n";
    }, $children[$parent])) . "$indent</ul>\n";
}

Example use:

$arrItems = [
    ['id' => 1, 'parent_id' => 0],
    ['id' => 2, 'parent_id' => 1],
    ['id' => 3,  'parent_id' => 2],
    ['id' => 4,  'parent_id' => 1],
];

echo toHTML(toTree($arrItems));

The above outputs:

<ul>
  <li>1
    <ul>
      <li>2
        <ul>
          <li>3
          </li>
        </ul>
      </li>
      <li>4
      </li>
    </ul>
  </li>
</ul>
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much. But can you explain how's "&$variable" works?
That is to make it a reference parameter. In this case it would also work without &, but then PHP copies the array that is passed as argument into the (new) function parameter variable. While with & the parameter variable really is a reference to the array that is passed as argument -- so without making a copy. See Passing by Reference
One more question, Is it possible to make it without using a reference parameter?

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.