【问题标题】:Best way to transform tag list into structured array from MySQL?将标签列表从 MySQL 转换为结构化数组的最佳方法?
【发布时间】:2018-08-09 20:56:18
【问题描述】:

我的数据库正在存储这样的列表:

ID | name
--- -----
1  | search
2  | search.categories
3  | search.categories.accessories
4  | search.categories.accessories.glasses
5  | search.categories.accessories.hats
6  | filters
7  | filters.payments
8  | filters.payments.creditcard
9  | filters.payments.debitcard

现在我想在一个递归数组中选择它,就像这样:

[
    name, childs[
        name, childs[ ... ],
        name, childs[ ... ],
        name, childs[
            name, childs[ ... ],
            name, childs[ ... ],
        ],
    ],
    name, childs[
        name, childs[ ... ],
        name, childs[ ... ],
        name, childs[
            name, childs[ ... ],
            name, childs[ ... ],
        ],
    ]
]

实现这一目标的最佳方法是什么?直接来自 MySQL 还是手动处理字符串?

【问题讨论】:

  • 您将不得不使用 php 来解析字符串并将它们添加到数组中。这也没有内置功能,你必须做点什么。有些问题讨论了如何使用“点符号”将值分配给数组,例如this one,这应该可以帮助您入门。此外,像这样在单个字符串字段中存储多个值(grandparent.parent.child.etc)通常被认为是不好的做法。
  • 我写了一个示例 PHP 函数来做类似的事情,但是使用邻接列表数据而不是像你这样的路径枚举数据。无论如何,它可以作为一个开始的例子。 stackoverflow.com/questions/3261228/…

标签: php mysql laravel


【解决方案1】:

如果您正在使用 Laravel,您可以使用 array_set 并使用表的 name 列作为键来构建嵌套数组,利用您已经以点表示法存储的优势。

尽管您没有公开这样做的目的是什么以及为什么要以这种方式构建此结构,但请遵循一种可能的方法。

  • 初始化一个空数组 ($structure = [])
  • 检索所有表记录并对其进行迭代(根据需要使用数据库选择或模型获取)
  • 对于每个表格行,执行array_set($structure, $listname, $value)

在你的例子中,我看不出$value 可能来自哪里,但我想你会理解这个想法。

$structure = [];
foreach($rows as $row)
{
    array_set($structure, $row->name, $value);
}

【讨论】:

    猜你喜欢
    • 2015-08-13
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    相关资源
    最近更新 更多