-1

I have an php array is below,

$two_dimention = array(
array("id"=>4, "name" => "Home", "parent" => 0, "depth" => 0),
array("id"=>5, "name" => "Menu 1", "parent" => 0, "depth" => 0),
array("id"=>6, "name" => "Menu 2", "parent" => 0, "depth" => 0),
array("id"=>8, "name" => "Menu 2.1", "parent" => 6, "depth" => 1),
array("id"=>10, "name" => "Menu 2.1.1", "parent" => 8,  "depth" => 2),
array("id"=>11, "name" => "Menu 2.1.2", "parent" => 8, "depth" => 2),
array("id"=>9, "name" => "Menu 2.2", "parent" => 6, "depth" => 1),
array("id"=>7, "name" => "Menu 3", "parent" => 0, "depth" => 0),
array("id"=>18, "name" => "Menu 3.1", "parent" => 7, "depth" => 1),
);

According to this $two_dimention array it will be created the multi-dimensional order list in HTML, that is look like below,

 <ul>
    <li>Home</li>
    <li>Menu 1</li>
    <li>Menu 2
        <ul>
            <li>Menu 2.1
                <ul>
                    <li>Menu 2.1.1</li>
                    <li>Menu 2.1.2</li>
                </ul>
            </li>
            <li>Menu 2.2</li>
        </ul>
    </li>
    <li>Menu 3
        <ul>
            <li>Menu 3.1</li>
        </ul>
    </li>
</ul>

How can I do this by PHP for/foreach loop?

Optimus Prime
  • 308
  • 6
  • 22

1 Answers1

1

Here is the answer, created nested arrays from multi-dimensional array with ref

function makeRecursive($d, $r = 0, $pk = 'parent', $k = 'id', $c = 'children')
{
    $m = [];
    foreach ($d as $e) {
        isset($m[$e[$pk]]) ?: $m[$e[$pk]] = [];
        isset($m[$e[$k]]) ?: $m[$e[$k]]   = [];
        $m[$e[$pk]][]                     = array_merge($e, [$c => &$m[$e[$k]]]);
    }
    return $m[$r]; // remove [0] if there could be more than one root nodes
}
function nested2ul($data)
{
    $result = [];
    if (sizeof($data) > 0) {
        $result[] = '<ul>';
        foreach ($data as $entry) {
            $result[] = sprintf(
                '<li>%s %s</li>',
                $entry['name'],
                nested2ul($entry['children'])
            );
        }
        $result[] = '</ul>';
    }
    return implode($result);
}
$temp= makeRecursive($two_dimention);
echo nested2ul($temp);

Demo

Output

<ul>
  <li>Home </li>
  <li>Menu 1 </li>
  <li>Menu 2
    <ul>
      <li>Menu 2.1
        <ul>
          <li>Menu 2.1.1 </li>
          <li>Menu 2.1.2 </li>
        </ul>
      </li>
      <li>Menu 2.2 </li>
    </ul>
  </li>
  <li>Menu 3
    <ul>
      <li>Menu 3.1 </li>
    </ul>
  </li>
</ul>
Rahul
  • 18,271
  • 7
  • 41
  • 60