转换MySQL表与相对于多维数组 [英] Convert MySQL table with relation to multi-dimensional array

查看:168
本文介绍了转换MySQL表与相对于多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个菜单表:

的id,蛞蝓,标签,父

家长有​​关系 ID ,所以如果你有:

Parent has a relation to id so if you had:

1,'富巴','富酒吧',NULL

这将是一个根项目,而

2,'富','富',1

将属于'富酒吧。然后,你可以有属于项目等。

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

我怎样才能变成PHP中的多维数组的菜单呢?所以,我可以做这样的事情:

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' ?>

我的要求是非常相似<一href=\"http://stackoverflow.com/questions/32077219/how-to-convert-db-table-with-parent-son-relation-to-multi-dimensional-array\">How到数据库表转换与父母的儿子关系多维数组但得到的答复有不工作;它不是递归的。

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.

推荐答案

下面是例子的foreach (非测试),可以做你想要的东西。

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

这篇关于转换MySQL表与相对于多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆