Reputation: 1702
Array
(
[0] => Array
(
[id] => 39
[parent_id] => 0
[sku] => Parent
)
[1] => Array
(
[id] => 40
[parent_id] => 39
[sku] => Child of parent id 39
)
[2] => Array
(
[id] => 41
[parent_id] => 40
[sku] => Child of child id 40
)
[3] => Array
(
[id] => 42
[parent_id] => 40
[sku] => Another child of child id 40
)
[4] => Array
(
[id] => 43
[parent_id] => 39
[sku] => Another child of parent id 39
)
etc..
)
I have here an associative arrays which basically is a parent - child relationship. There's been so many sample in the web on how to build a tree that help me a lot. But right now I just want to format my array to something like this:
> Parent --> first prefix ">"
>> Child of parent id 39 --> added two ">" prefixes
>>> Child of child id 40 --> added three ">" prefixes
>>> Another child of child id 40
>> Another child of parent id 39
and so on..
Update: This is how I build my tree for now:
function pdf_content($data, $parentId = 0)
{
$str = '';
foreach ($data as $row) {
if ($row['parent_id'] == $parentId) {
$str .= '<li>';
$str .= $row['sku'];
$str .= pdf_content($data, $row['id']);
$str .= '</li>';
}
}
if ($str) {
$str = "<ol class='dashed'>" . $str . '</ol>';
}
return $str;
}
// this is using the ol list style.
So first the children will have to get its parent and append the prefix ">".I already have a code to build a tree but formatting it to something like this got me stuck on a tree.
Upvotes: 2
Views: 135
Reputation: 590
I think this should do it.
function pdf_content($items, $parentId = 0, $prefix = '>')
{
$str = '';
foreach ($items as $item)
{
if ($item['parent_id'] == $parentId) {
$str .= '<li>';
$str .= $prefix.$item['sku'];
$str .= pdf_content($items, $item['id'], $prefix.'>');
$str .= '</li>';
}
}
if ($str) {
$str = "<ol class='dashed'>" . $str . '</ol>';
}
return $str;
}
$string = pdf_content($array);
This is what I get as the Output -
>Parent
>>Parent 39
>>>Parent 40
>>>Parent 40
>>Parent 39
Upvotes: 1
Reputation: 2587
To adding Prefix use recursive function with pass parameter $prefix = '>'
if child found then concatinate $prefix .= '>'
and pass in your Function if child not found then overwrite to $prefix = '>'
only
Upvotes: 1