Создание динамического массива меню с использованием php

Я хочу создать массив, который следует за форматом ниже, чтобы создать динамическое меню в PHP.

$array = [ ['id'=>1, 'childs'=>[]], ['id'=>2, 'childs'=>[ ['id'=>5, 'childs'=>[]], ['id'=>6, 'childs'=>[]] ]], ['id'=>3, 'childs'=>[ ['id'=>7, 'childs'=>[ ['id'=>8,'childs'=>[ ['id'=>10,'childs'=>[]] ]] ]] ]], ['id'=>4, 'childs'=>[]], ]; 

Данные в SQL

 id id_parent 1 0 2 0 3 0 4 0 5 2 6 2 7 3 8 7 9 8 

Хотя вы не прилагаете никаких усилий для решения своей проблемы, я отвечу на это, потому что это сложная задача, если вы не знакомы с некоторыми понятиями. Я также понимаю, что ваш вопрос не означает «динамический», поскольку он не является жестко запрограммированным.

Во-первых, конечный продукт – это не совсем то, что вы показываете, но он несколько избыточен, как вы настроили свой ожидаемый выход. По определению, заполненный массив под другим массивом будет дочерним ( «childs» ), поэтому нет необходимости хранить их в вспомогательном массиве с именем « childs ».

Чтобы создать этот массив, вы должны иметь возможность создавать массив, а затем также перемещаться по тому же массиву, который вы делаете. Вы должны быть осторожны с тем, чтобы не сделать осиротевшего ребенка, что означает, что у вас есть значение id_parent , но в вашем основном массиве нет соответствующего id . Он не будет отображаться в меню без дополнительного скрипта.

Я отметил, что зрители могут понять, что происходит, а не просто слепо копировать и вставлять. В заключение отметим, что я действительно не использую PHP-объектно-ориентированный рекурсивный массив Iterator (или другие классы итератора), поэтому вы должны их исследовать. Возможно, вы сможете сделать то же самое более эффективно:

 # Main array with parents/children $array = array( array( 'id'=>1, 'id_parent'=>0 ), array( 'id'=>2, 'id_parent'=>0 ), array( 'id'=>3, 'id_parent'=>0 ), array( 'id'=>4, 'id_parent'=>0 ), array( 'id'=>5, 'id_parent'=>2 ), array( 'id'=>6, 'id_parent'=>2 ), array( 'id'=>7, 'id_parent'=>3 ), array( 'id'=>8, 'id_parent'=>7 ), array( 'id'=>9, 'id_parent'=>8 ) ); /* ** @description This function is a recursive iterator, meaning it will ** traverse the current array and all children ** @param $curr [string|int] This is the current id value being ready to place ** @param $parent [string|int] This is the current parent id being searched ** @param $arr [array] This is the array that is being built for the menu structure ** @param $array [array] This is the array pool of ids and parent ids. We are going to pass by reference ** to update this array as we go to fix chicken-before-the-egg scenarios ** @param $rKey [int] This is the current key being iterated on in the main array pool */ function recurse($curr,$parent,$arr,&$array,$rKey) { # Loop through our menu array to try and match parents foreach($arr as $key => $value) { # If there is a match if($parent == $key) { # Remove the key/value pair from main array unset($array[$rKey]); # Add the id to our menu array $arr[$key][$curr] = array(); } # If there is no immediate parent match else { # If the value is an array, try and now look through it for parent, else just continue $arr[$key] = (is_array($value))? recurse($curr,$parent,$value,$array,$rKey) : $value; } } # Send back this current array return $arr; } /* ** @description This function takes your pool of ids and loops through them, sorting the menu items */ function getMenuArray($array) { # This is the final storage array $arr = array(); # First count to see how many are available $count = count($array); # Start looping for($i=0; $i<$count; $i++) { $row = $array[$i]; # If there are no parents, the just assign base menu if(empty($row['id_parent'])) { $arr[$row['id']] = array(); # Remove this key/value pair from main array since it's been used unset($array[$i]); } else { # Recurse what we currently have stored for the menu $new = recurse($row['id'],$row['id_parent'],$arr,$array,$i); # If the recurse function didn't find it's parent if(isset($array[$i])) { # add it to the back of the array $array[] = $row; # Remove the current array unset($array[$i]); # Recount how many are left to iterate through $count = count($array); } # If the parent was found else # Assign the $new array $arr = $new; } } # Return the array return $arr; } print_r(getMenuArray($array)); с # Main array with parents/children $array = array( array( 'id'=>1, 'id_parent'=>0 ), array( 'id'=>2, 'id_parent'=>0 ), array( 'id'=>3, 'id_parent'=>0 ), array( 'id'=>4, 'id_parent'=>0 ), array( 'id'=>5, 'id_parent'=>2 ), array( 'id'=>6, 'id_parent'=>2 ), array( 'id'=>7, 'id_parent'=>3 ), array( 'id'=>8, 'id_parent'=>7 ), array( 'id'=>9, 'id_parent'=>8 ) ); /* ** @description This function is a recursive iterator, meaning it will ** traverse the current array and all children ** @param $curr [string|int] This is the current id value being ready to place ** @param $parent [string|int] This is the current parent id being searched ** @param $arr [array] This is the array that is being built for the menu structure ** @param $array [array] This is the array pool of ids and parent ids. We are going to pass by reference ** to update this array as we go to fix chicken-before-the-egg scenarios ** @param $rKey [int] This is the current key being iterated on in the main array pool */ function recurse($curr,$parent,$arr,&$array,$rKey) { # Loop through our menu array to try and match parents foreach($arr as $key => $value) { # If there is a match if($parent == $key) { # Remove the key/value pair from main array unset($array[$rKey]); # Add the id to our menu array $arr[$key][$curr] = array(); } # If there is no immediate parent match else { # If the value is an array, try and now look through it for parent, else just continue $arr[$key] = (is_array($value))? recurse($curr,$parent,$value,$array,$rKey) : $value; } } # Send back this current array return $arr; } /* ** @description This function takes your pool of ids and loops through them, sorting the menu items */ function getMenuArray($array) { # This is the final storage array $arr = array(); # First count to see how many are available $count = count($array); # Start looping for($i=0; $i<$count; $i++) { $row = $array[$i]; # If there are no parents, the just assign base menu if(empty($row['id_parent'])) { $arr[$row['id']] = array(); # Remove this key/value pair from main array since it's been used unset($array[$i]); } else { # Recurse what we currently have stored for the menu $new = recurse($row['id'],$row['id_parent'],$arr,$array,$i); # If the recurse function didn't find it's parent if(isset($array[$i])) { # add it to the back of the array $array[] = $row; # Remove the current array unset($array[$i]); # Recount how many are left to iterate through $count = count($array); } # If the parent was found else # Assign the $new array $arr = $new; } } # Return the array return $arr; } print_r(getMenuArray($array)); с # Main array with parents/children $array = array( array( 'id'=>1, 'id_parent'=>0 ), array( 'id'=>2, 'id_parent'=>0 ), array( 'id'=>3, 'id_parent'=>0 ), array( 'id'=>4, 'id_parent'=>0 ), array( 'id'=>5, 'id_parent'=>2 ), array( 'id'=>6, 'id_parent'=>2 ), array( 'id'=>7, 'id_parent'=>3 ), array( 'id'=>8, 'id_parent'=>7 ), array( 'id'=>9, 'id_parent'=>8 ) ); /* ** @description This function is a recursive iterator, meaning it will ** traverse the current array and all children ** @param $curr [string|int] This is the current id value being ready to place ** @param $parent [string|int] This is the current parent id being searched ** @param $arr [array] This is the array that is being built for the menu structure ** @param $array [array] This is the array pool of ids and parent ids. We are going to pass by reference ** to update this array as we go to fix chicken-before-the-egg scenarios ** @param $rKey [int] This is the current key being iterated on in the main array pool */ function recurse($curr,$parent,$arr,&$array,$rKey) { # Loop through our menu array to try and match parents foreach($arr as $key => $value) { # If there is a match if($parent == $key) { # Remove the key/value pair from main array unset($array[$rKey]); # Add the id to our menu array $arr[$key][$curr] = array(); } # If there is no immediate parent match else { # If the value is an array, try and now look through it for parent, else just continue $arr[$key] = (is_array($value))? recurse($curr,$parent,$value,$array,$rKey) : $value; } } # Send back this current array return $arr; } /* ** @description This function takes your pool of ids and loops through them, sorting the menu items */ function getMenuArray($array) { # This is the final storage array $arr = array(); # First count to see how many are available $count = count($array); # Start looping for($i=0; $i<$count; $i++) { $row = $array[$i]; # If there are no parents, the just assign base menu if(empty($row['id_parent'])) { $arr[$row['id']] = array(); # Remove this key/value pair from main array since it's been used unset($array[$i]); } else { # Recurse what we currently have stored for the menu $new = recurse($row['id'],$row['id_parent'],$arr,$array,$i); # If the recurse function didn't find it's parent if(isset($array[$i])) { # add it to the back of the array $array[] = $row; # Remove the current array unset($array[$i]); # Recount how many are left to iterate through $count = count($array); } # If the parent was found else # Assign the $new array $arr = $new; } } # Return the array return $arr; } print_r(getMenuArray($array)); с # Main array with parents/children $array = array( array( 'id'=>1, 'id_parent'=>0 ), array( 'id'=>2, 'id_parent'=>0 ), array( 'id'=>3, 'id_parent'=>0 ), array( 'id'=>4, 'id_parent'=>0 ), array( 'id'=>5, 'id_parent'=>2 ), array( 'id'=>6, 'id_parent'=>2 ), array( 'id'=>7, 'id_parent'=>3 ), array( 'id'=>8, 'id_parent'=>7 ), array( 'id'=>9, 'id_parent'=>8 ) ); /* ** @description This function is a recursive iterator, meaning it will ** traverse the current array and all children ** @param $curr [string|int] This is the current id value being ready to place ** @param $parent [string|int] This is the current parent id being searched ** @param $arr [array] This is the array that is being built for the menu structure ** @param $array [array] This is the array pool of ids and parent ids. We are going to pass by reference ** to update this array as we go to fix chicken-before-the-egg scenarios ** @param $rKey [int] This is the current key being iterated on in the main array pool */ function recurse($curr,$parent,$arr,&$array,$rKey) { # Loop through our menu array to try and match parents foreach($arr as $key => $value) { # If there is a match if($parent == $key) { # Remove the key/value pair from main array unset($array[$rKey]); # Add the id to our menu array $arr[$key][$curr] = array(); } # If there is no immediate parent match else { # If the value is an array, try and now look through it for parent, else just continue $arr[$key] = (is_array($value))? recurse($curr,$parent,$value,$array,$rKey) : $value; } } # Send back this current array return $arr; } /* ** @description This function takes your pool of ids and loops through them, sorting the menu items */ function getMenuArray($array) { # This is the final storage array $arr = array(); # First count to see how many are available $count = count($array); # Start looping for($i=0; $i<$count; $i++) { $row = $array[$i]; # If there are no parents, the just assign base menu if(empty($row['id_parent'])) { $arr[$row['id']] = array(); # Remove this key/value pair from main array since it's been used unset($array[$i]); } else { # Recurse what we currently have stored for the menu $new = recurse($row['id'],$row['id_parent'],$arr,$array,$i); # If the recurse function didn't find it's parent if(isset($array[$i])) { # add it to the back of the array $array[] = $row; # Remove the current array unset($array[$i]); # Recount how many are left to iterate through $count = count($array); } # If the parent was found else # Assign the $new array $arr = $new; } } # Return the array return $arr; } print_r(getMenuArray($array)); 

Дает тебе:

 Array ( [1] => Array ( ) [2] => Array ( [5] => Array ( ) [6] => Array ( ) ) [3] => Array ( [7] => Array ( [8] => Array ( [9] => Array ( ) ) ) ) [4] => Array ( ) )