MYSQL父子同表; PHP 将子代嵌套在父代中作为多维数组
Posted
技术标签:
【中文标题】MYSQL父子同表; PHP 将子代嵌套在父代中作为多维数组【英文标题】:MYSQL Parent Child Same Table; PHP Nest Children Within Parents as a Multidimensional-Array 【发布时间】:2012-12-03 00:39:52 【问题描述】:mysql 返回一个数组,如下所示。我正在使用 column: 'id_parent' 来自引用表以创建层次结构。因此,“id”为 2 的条目可以是任何“id_parent”为 2 的条目的父项,依此类推。
Array
(
[1] => Array
(
[id] => 2
[name] => About
[id_parent] => NULL
)
[2] => Array
(
[id] => 4
[name] => About Child
[id_parent] => 2
)
[3] => Array
(
[id] => 5
[name] => About Child's Child
[id_parent] => 4
)
)
如何将子元素嵌套到其父数组中的数组中
Array
(
[1] => Array
(
[id] => 2
[name] => About
[id_parent] =>
[children] => Array
(
[id] => 4
[name] => About Child
[id_parent] => 2
[children] => Array
(
[id] => 5
[name] => About Child's Child
[id_parent] => 4
)
)
)
)
【问题讨论】:
【参考方案1】:引用,其优点是顺序无关紧要(子节点可以在其父节点之前):
$tree = array('NULL' => array('children' => array()));
foreach($array as $item)
if(isset($tree[$item['id']]))
$tree[$item['id']] = array_merge($tree[$item['id']],$item);
else
$tree[$item['id']] = $item;
$parentid = is_null($item['id_parent']) ? 'NULL' : $item['id_parent'];
if(!isset($tree[$parentid])) $tree[$parentid] = array('children' => array());
//this & is where the magic happens: any alteration to $tree[$item['id']
// will reflect in the item $tree[$parentid]['children'] as they are the same
// variable. For instance, adding a child to $tree[$item['id']]['children]
// will be seen in
// $tree[$parentid]['children'][<whatever index $item['id'] has>]['children]
$tree[$parentid]['children'][] = &$tree[$item['id']];
$result = $tree['NULL']['children'];
//always unset references
unset($tree);
【讨论】:
我现在要试试这个。感谢您的快速回复。 第一次看时完全错过了那里的参考资料。很棒的小sn-p! 完美!看到它的工作我很震惊。现在逐行剖析这个漂亮的款待。谢谢! 哇,这是真正的交易。试图通过数组遍历数组映射数组减少来做到这一点,我变得太复杂了。这很简单,很有效,谢谢。以上是关于MYSQL父子同表; PHP 将子代嵌套在父代中作为多维数组的主要内容,如果未能解决你的问题,请参考以下文章