php将数组转换成数据库的分层嵌套集 [英] php convert array into a hierarchical nested set for database
本文介绍了php将数组转换成数据库的分层嵌套集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我读了这个:
http:// mikehillyer。 com / articles / manage-hierarchical-data-in-mysql /
我正在使用mysql和php
我需要的是脚本只将一次旧数据转换成具有左/右值的数据。
And i'm using mysql and php What I need is script that convert only for one time the old data into data with the left/right values.
我不需要添加/更新东西。
I don't need to add/update things.
php数据
$in_array = array (
array(
'id' => 400,
'n' => 'Sub 1a',
's' => array (
array (
'n' => 'Sub 1b',
'id' => 421,
's' => array (
array (
'n' => 'Sub 1c',
'id' => 422,
)
)
)
)
),
array(
'id' => 500,
'n' => 'Sub 2a',
's' => array (
array (
'n' => 'Sub 2b',
'id' => 521,
's' => array (
array (
'n' => 'Sub 3b',
'id' => 522,
)
)
)
)
)
);
目前我正在尝试用这个脚本来解决这个问题,但是不能像这样。应该
At the moment i'm trying to solve this with this script but that don't work like it should.
$a_newTree = array();
function rebuild_tree($parent, $left) {
global $a_newTree;
$indexed = array();
// the right value of this node is the left value + 1
$right = $left+1;
// get all children of this node
foreach($parent as $cat){
// recursive execution of this function for each
// child of this node
// $right is the current right value, which is
// incremented by the rebuild_tree function
if(is_array($cat) && array_key_exists('s',$cat)){
$indexed['n'] = $cat['n'];
$right = rebuild_tree($cat, $right);
}
}
// we've got the left value, and now that we've processed
// the children of this node we also know the right value
array_push($a_newTree,array(':lft'=>$left,':rgt'=>$right,':name'=>'bla'));
// return the right value of this node + 1
return $right+1;
}
rebuild_tree($in_array, 1);
我可以访问mysql和查询,所以输出如下
I can access mysql and query so the output is like this
Sub 1a | Sub 1b | Sub 1c
Sub 1a | Sub 1b | Sub 1d
Sub 1a | Sub 1b | Sub 1e
Sub 1a | Sub 1f | Null
Sub 1a | Sub 1g | Null
Sub 2a | Sub 2b | Sub 2c
使用这些数据,我做了上面的数组。
With that data I made the array above.
推荐答案
数组不是oke。
这是工作
$in_array = array (
// array(
'id' => 400,
'n' => 'Sub 1a',
's' => array (
// array (
'n' => 'Sub 1b',
'id' => 421,
's' => array (
// array (
'n' => 'Sub 1c',
'id' => 422,
// )
)
// )
// )
),
array(
'id' => 500,
'n' => 'Sub 2a',
's' => array (
// array (
'n' => 'Sub 2b',
'id' => 521,
's' => array (
// array (
'n' => 'Sub 3b',
'id' => 522,
// )
)
// )
)
)
);
$a_newTree = array();
function rebuild_tree($parent, $left) {
global $a_newTree;
$indexed = array();
$right = $left+1;
if(array_key_exists('n',$parent)){
$indexed['n'] = $parent['n'];
}else{
$indexed['n'] = '?';
}
foreach($parent as $cat){
if(is_array($cat)){
$right = rebuild_tree($cat, $right);
}
}
array_push($a_newTree,array(':lft'=>$left,':rgt'=>$right,':name'=>$indexed['n']));
return $right+1;
}
rebuild_tree($in_array, 1);
这篇关于php将数组转换成数据库的分层嵌套集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文