可能重复:
根据父 ID 值将数组从一维转换为多维
我正在尝试将一堆类别安排到他们的层次结构中。我有一个类别的 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;
}
}