我需要将我的嵌套集结构(mysql)转换为这个空间树的json
1)http://blog.thejit.org/wp-content/jit-1.0a/examples/spacetree.html http://blog.thejit.org/wp-content/jit-1.0a/examples/spacetree.html
我发现这个函数可以从嵌套集合创建一个数组:
2)http://semlabs.co.uk/journal/converting-nested-set-model-data-in-to-multi-Dimensions-arrays-in-php http://semlabs.co.uk/journal/converting-nested-set-model-data-in-to-multi-dimensional-arrays-in-php
我还可以使用 PHP 函数 json_encode 将 php 数组转换为 json
我的问题:函数 Nestify (来自第二个链接)给了我不完全是我需要的。我需要这样的东西:http://pastebin.com/m68752352 http://pastebin.com/m68752352
你能帮我更改函数“nestify”,以便它为我提供正确的数组吗?
这是这个函数的再一次:
function nestify( $arrs, $depth_key = 'depth' )
{
$nested = array();
$depths = array();
foreach( $arrs as $key => $arr ) {
if( $arr[$depth_key] == 0 ) {
$nested[$key] = $arr;
$depths[$arr[$depth_key] + 1] = $key;
}
else {
$parent =& $nested;
for( $i = 1; $i <= ( $arr[$depth_key] ); $i++ ) {
$parent =& $parent[$depths[$i]];
}
$parent[$key] = $arr;
$depths[$arr[$depth_key] + 1] = $key;
}
}
return $nested;
}
下面的代码片段应该可以解决问题,改编自我在网上找到的一些 PHP Doctrine 代码:
function toHierarchy($collection)
{
// Trees mapped
$trees = array();
$l = 0;
if (count($collection) > 0) {
// Node Stack. Used to help building the hierarchy
$stack = array();
foreach ($collection as $node) {
$item = $node;
$item['children'] = array();
// Number of stack items
$l = count($stack);
// Check if we're dealing with different levels
while($l > 0 && $stack[$l - 1]['depth'] >= $item['depth']) {
array_pop($stack);
$l--;
}
// Stack is empty (we are inspecting the root)
if ($l == 0) {
// Assigning the root node
$i = count($trees);
$trees[$i] = $item;
$stack[] = & $trees[$i];
} else {
// Add node to parent
$i = count($stack[$l - 1]['children']);
$stack[$l - 1]['children'][$i] = $item;
$stack[] = & $stack[$l - 1]['children'][$i];
}
}
}
return $trees;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)