【问题标题】:Adding prefix '>' from my array tree从我的数组树中添加前缀“>”
【发布时间】:2016-03-04 08:19:43
【问题描述】:
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.

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

【问题讨论】:

  • 你能更新一下你是如何构建树的问题吗?
  • 嗨@Dwijen,请查看我更新的帖子。
  • @ChetanAmeta,我已经有了 buildTree 函数。我的问题是我希望使用前缀显示结果的方式。

标签: php arrays laravel tree treeview


【解决方案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

【讨论】:

    【解决方案2】:

    要添加前缀,请使用带有传递参数 $prefix = '&gt;' 的递归函数,如果找到子项,则连接 $prefix .= '&gt;' 并传入您的函数,如果未找到子项,则仅覆盖到 $prefix = '&gt;'

    【讨论】:

    • 嗨,你能看到我更新的帖子吗?我添加了构建树的功能。也许你可以帮帮我..
    • 你好,请查看制作树的链接我总是用它来制作树类别leon.vankammen.eu/tech/…
    猜你喜欢
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 2011-11-28
    • 2013-09-13
    • 2021-11-03
    • 1970-01-01
    相关资源
    最近更新 更多