gpt4 book ai didi

php - 如何将平面数组排序为多维树

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:09:52 24 4
gpt4 key购买 nike

我有一张 table

id    catagory      suboff

1 software 0
2 programming 1
3 Testing 1
4 Designing 1
5 Hospital 0
6 Doctor 5
7 Nurses 5
9 Teaching 0
10 php programming 2
11 .net programming 2

如何编写一个代码来获取一个基于suboff的多维数组中的所有这些信息,如下所示,

-software
--programming
---php programming
--- .net programming
--testing
--designing
-hospital
--doctor
--nurses
-teaching

最佳答案

假设 MySQL 作为您的数据库引擎:

// We'll need two arrays for this
$temp = $result = array();

// Get the data from the DB
$table = mysql_query("SELECT * FROM table");

// Put it into one dimensional array with the row id as the index
while ($row = mysql_fetch_assoc($table)) {
$temp[$row['id']] = $row;
}

// Loop the 1D array and create the multi-dimensional array
for ($i = 1; isset($temp[$i]); $i++) {
if ($temp[$i]['suboff'] > 0) {
// This row has a parent
if (isset($temp[$temp[$i]['suboff']])) {
// The parent row exists, add this row to the 'children' key of the parent
$temp[$temp[$i]['suboff']]['children'][] =& $temp[$i];
} else {
// The parent row doesn't exist - handle that case here
// For the purposes of this example, we'll treat it as a root node
$result[] =& $temp[$i];
}
} else {
// This row is a root node
$result[] =& $temp[$i];
}
}

// unset the 1D array
unset($temp);

// Here is the result
print_r($result);

使用references对于这样的工作。

关于php - 如何将平面数组排序为多维树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7874849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com