0

I have a menu table:

id, slug, label, parent

Parent has a relation to id so if you had:

1, 'foo-bar', 'Foo Bar', NULL

This would be a root item whereas:

2, 'foo', 'Foo ', 1

Would belong to 'foo-bar'. Then you could have items belonging to foo and so on.

How can I turn this into a multi-dimensional menu array in PHP? So I can do things like:

<?= $menu['foo-bar']['foo'] // echos 'Foo' ?>

My requirements are very similar to How to convert DB table with parent son relation to multi-dimensional array but the answer there doesn't work; it isn't recursive.

1 Answer 1

1

Here is example of foreach (non-tested) that can do something that you want.

<?php
// $results is your data from database
$menu = array();

foreach($results as $k => $result) {
  $key = $result['id'];  
  $parent = $result['parent'];
  if(!empty($parent)){
   array_push($menu[$parent]['parents'], $result);
  } else {
    unset($results[$k]['parent'];
    $menu[$key] = $result;
  }
}

var_dump($menu);
Sign up to request clarification or add additional context in comments.

Comments

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.