Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

php - How to create multi-dimensional array from a list?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

Having an explicit 'children' key is usually preferable to the structure you're proposing, but feel free to modify as needed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...