重複の可能性:
親ID値に基づいて配列を1次元から多次元に変換する
たくさんのカテゴリをそれらの階層に配置しようとしています。cid
(カテゴリID)、、title
(parent
親ID)のみを格納するカテゴリのSQLテーブルがあります。
まだ完了していませんが、基本的に、カテゴリに親がある場合、参照によってそれを取得しようとしているところに行き詰まっています(**動作していません**の行を参照)。変更を反映するように$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;
}
}