I have an array of locations. Each of these locations can have child locations. Each of the child locations can also have children, and so on:
$locations = array(
array("id" => 1, "parent_id" => 0, "name" => "England"),
array("id" => 2, "parent_id" => 0, "name" => "Scotland"),
array("id" => 3, "parent_id" => 0, "name" => "Ireland"),
array("id" => 4, "parent_id" => 0, "name" => "Wales"),
array("id" => 5, "parent_id" => 1, "name" => "East England"),
array("id" => 6, "parent_id" => 1, "name" => "London"),
array("id" => 7, "parent_id" => 6, "name" => "West London"),
array("id" => 8, "parent_id" => 6, "name" => "East London"),
array("id" => 9, "parent_id" => 1, "name" => "East Midlands"),
array("id" => 10, "parent_id" => 9, "name" => "Derbyshire")
);
I want to re-structure this array so that the children are arrays of the parent. Something like this (untested):
$locations = array("id" => 1, "parent_id" => 0, "name" => "England", "children" => array(
array("id" => 5, "parent_id" => 1, "name" => "East England"),
array("id" => 6, "parent_id" => 1, "name" => "London", "children" => array(
array("id" => 7, "parent_id" => 6, "name" => "West London"),
array("id" => 8, "parent_id" => 6, "name" => "East London")))));
This is so I can then print them out using indents like so:
LOCATIONS
England
- East England
- London
-- West London
-- East London
- East Midlands
-- Derbyshire
Scotland
Ireland
Wales
I have tried several ways, like grouping them by parent ID, but I just can't work out the logic for this, and there may be a better way of doing it (recursion, perhaps?).
Many thanks.