我的数据库正在存储这样一个列表:
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/