[英]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: 父代与id
有关系,因此如果您有:
1, 'foo-bar', 'Foo Bar', NULL
This would be a root item whereas: 这将是一个根项目,而:
2, 'foo', 'Foo ', 1
Would belong to 'foo-bar'. 将属于“ foo-bar”。 Then you could have items belonging to foo
and so on. 然后,您可以拥有属于foo
项目,依此类推。
How can I turn this into a multi-dimensional menu array in PHP? 如何在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; 我的要求与如何将具有父子关系的DB表转换为多维数组非常相似,但是答案不起作用。 it isn't recursive. 它不是递归的。
Here is example of foreach
(non-tested) that can do something that you want. 这是可以进行所需操作的foreach
(未经测试)示例。
<?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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.