如何建立从列表多维数组? [英] How to create multi-dimensional array from a list?
本文介绍了如何建立从列表多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有父ID类别在MySQL中的列表。如何创建从列表中选择PHP数组。
I have a list of categories in MySQL with parent ID. How can I create a PHP array from the list.
ID Category Parent_ID
1 Car NULL
2 Education NULL
3 Mathematics 2
4 Physics 2
5 Astrophysics 4
我要产生这种结构的阵列
I want to produce an array of this structure
array(
"Car" => "1",
"Education" => array("Mathematics" => "2", "Physics" => array("Astrophysics" => "4"))
);
由于事实上,键/值并不重要,因为我将与其他栏目工作了。我只是想知道如何扫描列表中,并产生多级列表。
As a matter of fact, key/value is not important as I will work with other columns too. I just want to know how to scan the list and produce multi-level list.
推荐答案
一些非常简单的递归构建树结构:
Some very simple recursion to build a tree structure:
function buildTree(array $data, $parent = null) {
$branch = array();
foreach ($data as $row) {
if ($row['parent_id'] == $parent) {
$row['children'] = buildTree($data, $row['id']);
$branch[] = $row;
}
}
return $branch;
}
$tree = buildTree($rowsFromDatabase);
有一个明确的'孩子'
键通常是preferable给你提出的结构,但随时根据需要修改。
Having an explicit 'children'
key is usually preferable to the structure you're proposing, but feel free to modify as needed.
这篇关于如何建立从列表多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文