I'm storing an infinitely nested directory structure in mysql by assigning a "parent_album_id" to each "album" (unless it's at the top level, in which case it does not have a parent_album_id).
I first grab an array of all the albums from the database and change each albums key to it's "id" (autoincrement id).
Next, I want to reorganize the array of albums into a multidemensional array, storing child albums in 'children' for each album. I've had some success. The following code works fine if I only need to go down one level in the array, but if I go down more than one level it loses the full structure of the array. This is because when I recursively call array_search_key I don't pass the full array, just the next level that I want to search.
How can I recursively search through the array, but return the entire multidimensional array of albums?
foreach ($albums as &$album){
if($album['parent_album_id']){ // Move album if it has a parent
$insert_album = $album;
unset($albums[$album['id']]); // Remove album from the array, since we are going to insert it into its parent
$results = array_search_key($album['parent_album_id'],$albums,$insert_album, $albums);
if($results){
$albums = $results;
}
}
}
function array_search_key( $needle_key, $array , $insert_album) {
foreach($array AS $key=>&$value){
if($key == $needle_key) {
$array[$key]['children'][$insert_album['id']] = $insert_album;
return $array;
}
if(is_array($value) && is_array($value['children'])){
if( ($result = array_search_key($needle_key, $value['children'], $insert_album)) !== false)
return $result;
}
}
return false;
}