php - 从 MySQL 将标签列表转换为结构化数组的最佳方法?

标签 php mysql laravel

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

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 还是手动处理字符串?

最佳答案

如果您使用的是 Laravel,您可以通过使用 array_set 并将表的 name 列用作键来构建嵌套数组,利用您已经存储的在点符号上。

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

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

在您的示例中,我看不到 $value 的来源,但我想您会理解这个想法。

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

关于php - 从 MySQL 将标签列表转换为结构化数组的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51775639/

相关文章:

php - 对于大文本我应该使用哪种哈希方法? - PHP/MYSQL

mysql - 在 web.config 中设置连接字符串是否存在安全漏洞? (ASP.NET MVC、 Entity Framework )

php - 在 Laravel 5.4 中将空值转换为空字符串

php - htaccess - 使用 php 和 mysql 重写 url

javascript - 通过.js将值传递给php,然后在SQL语句中使用

MySQL触发器将多个字符串连接成一个变量

php - 如何在 laravel 中使用 ajax 正确实现简单的搜索功能?

laravel - ramsey/uuid 如何在全局范围内独一无二?

php - 自动页面刷新,无需重新加载整个页面

java - 尽管语句中存在数据,Blob 字段自动设置为 null