I’ve been on this for two days now and I’m completely stuck. Google and SO couldn’t help me further and I’m overlooking something….
This is what I want
Home
Typography
404 Page not found
The company
The company/Team
The company/Team/Rick
The company/Team/Rick/Opleiding
The company/Team//Rob
The company/Office
The company/Office/Contact
The company/Office/Route
This is my array
Array
(
[0] => Array
(
[id] => 55
[parent_id] => 0
[title] => Home
[sub] => Array
(
)
)
[1] => Array
(
[id] => 27
[parent_id] => 0
[title] => Typography
[sub] => Array
(
)
)
[2] => Array
(
[id] => 56
[parent_id] => 0
[title] => 404 Page not found
[sub] => Array
(
)
)
[3] => Array
(
[id] => 68
[parent_id] => 0
[title] => The company
[sub] => Array
(
[0] => Array
(
[id] => 73
[parent_id] => 68
[title] => Team
[sub] => Array
(
[0] => Array
(
[id] => 74
[parent_id] => 73
[title] => Rick
[sub] => Array
(
[0] => Array
(
[id] => 79
[parent_id] => 74
[title] => Opleiding
[sub] => Array
(
)
)
)
)
[1] => Array
(
[id] => 75
[parent_id] => 73
[title] => Rob
[sub] => Array
(
)
)
)
)
[1] => Array
(
[id] => 76
[parent_id] => 68
[title] => Office
[sub] => Array
(
[0] => Array
(
[id] => 78
[parent_id] => 76
[title] => Contact
[sub] => Array
(
)
)
[1] => Array
(
[id] => 77
[parent_id] => 76
[title] => Route
[sub] => Array
(
)
)
)
)
)
)
)
This is what I have so far
public function BuildTitle($array, &$parents = null)
{
$html = '';
foreach($array as $page)
{
if($page['parent_id'] != 0)
{
$html .= $parents.'/'.$page['title'].'<br/>';
$parents = $parents.'/'.$page['title'];
}
else
{
$html .= $page['title'].'<br/>';
$parents = $page['title'];
}
$html .= $this->BuildTitle($page['sub'], $parents);
}
return $html;
}
And that returns
Home
Typography
404 Page not found
The company
The company/Team
The company/Team/Rick
The company/Team/Rick/Opleiding
The company/Team/Rick/Opleiding/Rob
The company/Team/Rick/Opleiding/Rob/Office
The company/Team/Rick/Opleiding/Rob/Office/Contact
The company/Team/Rick/Opleiding/Rob/Office/Contact/Route
Parent/child relations are unlimited. What am I doing wrong/missing? Thanks in advance!
You’re modifying the same
$parentsvalue in every iteration. So, as long as the parent isn’t 0, it just appends the current child to whatever the path is.Imagine for instance you had the following scenario:
When processing
foo, it’d start with$parents = 'foo'.It then goes through each of the children, updating
$parents:barmakes$parents = $parents . '/' . $page['title'] = 'foo' . '/' . 'bar' = 'foo/bar'.bazmakes$parents = $parents . '/' . $page['title'] = 'foo/bar' . '/' . 'bar' = 'foo/bar/baz'.What you want is this: