2016-03-04 55 views
2
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.. 
) 

我在这里有一个基本上是父 - 子关系的关联数组。网络上有很多关于如何构建能够帮助我很多的树的示例。但是现在,我只想我的数组格式化为这样的事情:从我的数组树中添加前缀'>'

> 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.. 

更新: 这是我如何建立我的树现在:

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. 

所以首先孩子将获得它的父母和附加前缀“>”。我已经有一个代码来建立一棵树,但格式化为这样的东西让我卡在一棵树上。

+1

你可以更新你是如何构建的树的问题? – Dwijen

+0

嗨@Dwijen,请看我更新的帖子。 –

+0

@ChetanAmeta,我已经有了buildTree函数。我的问题是我想要使用前缀显示结果的方式。 –

回答

1

我想这应该这样做。

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); 

这是我得到的输出 -

>Parent 
    >>Parent 39 
     >>>Parent 40 
     >>>Parent 40 
    >>Parent 39 
+0

做到了!哈哈。感谢许多男士。 –

1

要添加前缀使用带通参数$prefix = '>'递归函数,如果孩子找到,那么concatinate $prefix .= '>'和你的函数传递,如果孩子找不到,则改写为$prefix = '>'

+0

你好,你能看到我更新的帖子。我添加了我的函数来构建一棵树。也许你可以帮助我.. –

+0

你好,请参阅使树的链接我总是用它来制作树分类http://leon.vankammen.eu/tech/storing-retrieving-hierarchical-trees-between-php-and -mysql.html –