I have a list of categories in MySQL with parent ID. How can I create a PHP array from the list.
ID Category Parent_ID 1 Car NULL 2 Education NULL 3 Mathematics 2 4 Physics 2 5 Astrophysics 4
I want to produce an array of this structure
array( "Car" => "1", "Education" => array("Mathematics" => "2", "Physics" => array("Astrophysics" => "4")) );
As a matter of fact, key/value is not important as I will work with other columns too. I just want to know how to scan the list and produce multi-level list.
Some very simple recursion to build a tree structure:
Having an explicit
'children'key is usually preferable to the structure you're proposing, but feel free to modify as needed.