如何从列表创建多维数组? [英] How to create multi-dimensional array from a list?

查看:24
本文介绍了如何从列表创建多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 MySQL 中有一个带有父 ID 的类别列表.如何从列表中创建一个 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);

拥有一个明确的 'children' 键通常比您提议的结构更可取,但您可以根据需要随意修改.

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

这篇关于如何从列表创建多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆