PHP get array property by reference
I’m trying to arrange a bunch of categories into their hierarchies. I have an SQL table for the categories that only stores their cid (category id), title, parent (parent id).
It’s not done yet but basically I’m stuck at the point where if a category has a parent then I’m trying to grab it by reference (see line **NOT WORKING**). I want to update the $return array to reflect the change
// 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;
}
Total Views: 15 Today Views: 0














