简体   繁体   中英

Convert MySQL table with relation to multi-dimensional array

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM