【发布时间】:2012-12-11 13:19:18
【问题描述】:
可能重复:
Converting an array from one to multi-dimensional based on parent ID values
我正在尝试将一堆类别排列到它们的层次结构中。我有一个类别的 SQL 表,仅存储它们的 cid(类别 ID)、title、parent(父 ID)。
它还没有完成,但基本上我被困在如果一个类别有一个父类别,那么我试图通过引用来获取它(参见 **NOT WORKING** 行)。我想更新 $return 数组以反映更改
// returns categories in their correct heierarchy
function organize_categories( $array ) {
$return = array();
// instead of retyping the same thing over and over again
function create_record( $data ) {
return array(
'title' => $data->title,
'children' => array()
);
}
// go over each row
foreach( $array as $id => $cat ) {
// if it doesn't have a parent (AKA 0)
if( !$cat->parent ) {
$return[ $id ] = create_record( $cat );
} else {
// get reference of parent **NOT WORKING**
$parent =& search_category( $cat->parent , $return );
if( $parent )
$parent[ 'children' ][ $id ] = create_record( $cat );
else
$return[ $id ] = create_record( $cat );
}
}
return $return;
}
function search_category( $pid , $array ) {
// if found within the immediate children
if( isset( $array[ $pid ] ) ) return $array[ $pid ];
// otherwise dig deeper and recurse
else {
foreach( $array as $id => $arr ) {
$find =& search_category( $pid , $arr[ 'children' ] );
if( $find ) return $find;
}
}
return FALSE;
}
编辑: 万一有人也遇到这个问题,这里是完整的递归解决方案
function &search_category( $pid , &$array ) {
// if found within the immediate children
if( isset( $array[ $pid ] ) ) return $array[ $pid ];
// otherwise dig deeper and recurse
else {
foreach( $array as &$arr ) {
$find =& search_category( $pid , $arr[ 'children' ] );
if( $find ) return $find;
}
}
【问题讨论】:
-
this 也可能对您有所帮助。
标签: php arrays variables reference