我在PHP有一個數據結構來連接使用Telnet這樣的開關:PHP陣列樹狀結構DB樹結構
Array
(
[172.1.1.2] => Array
(
[0] => Array
(
[IP] => 172.1.1.1
[PlatformBrand] => dlink
)
[1] => Array
(
[IP] => 172.1.1.5
[PlatformBrand] => dlink
)
[2] => Array
(
[IP] => 172.1.1.7
[PlatformBrand] => dlink
)
[3] => Array
(
[IP] => 172.1.1.8
[PlatformBrand] => dlink
)
)
[172.1.1.6] => Array
(
[0] => Array
(
[IP] => 172.1.1.10
[PlatformBrand] => dlink
)
)
[172.1.1.7] => Array
(
[0] => Array
(
[IP] => 172.1.1.11
[PlatformBrand] => dlink
)
[1] => Array
(
[IP] => 172.1.1.14
[PlatformBrand] => dlink
)
)
)
但我想轉換成樹這個像這樣的結構:
CREATE TABLE `network_equipment_class` (
`id` int(11) NOT NULL,
`ip` varchar(15) NOT NULL,
`parent` int(11) NOT NULL,
`sort` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
id | ip | parent | sort
--------------------------------
1 | 172.1.1.2 | 0 | 0
2 | 172.1.1.1 | 1 | 0
3 | 172.1.1.5 | 1 | 1
4 | 172.1.1.7 | 1 | 2
5 | 172.1.1.8 | 1 | 3
6 | 172.1.1.6 | 0 | 1
7 | 172.1.1.10 | 6 | 0
8 | 172.1.1.11 | 4 | 0
9 | 172.1.1.14 | 4 | 1
對於PHP> = 5.3來書寫功能代碼,任何想法或任何建議?
UPDATE: 這裏是我寫的代碼,但不能使用:
function createDBTree($IP, $dbTree){
if (!is_array($dbTree) || $dbTree == array()) {
$dbTree = array('ip' => $IP);
} else {
foreach ($dbTree as $dbkey => $tmpdbvalue) {
if(is_array($tmpdbvalue) && $arr !== array()) {
if (!isset($tmpdbvalue['children'])) $dbTree = $this->createDBTree($IP, $tmpdbvalue['children']);
} else {
if ($tmpdbvalue['ip'] == $IP) $tmpdbvalue['children'] = array('ip' => $IP);
}
}
}
return $dbTree;
}
最後,我將完成結構:
172.1.1.2 => 172.1.1.1
=> 172.1.1.5
=> 172.1.1.7 => 172.1.1.11 => ... => ...
=> 172.1.1.14
=> ...
=> 172.1.1.8
=> ...
172.1.1.6 => 172.1.1.10
=> ...
...
以'foreach'開頭。我們不會在這裏爲你寫代碼。 –
我已經嘗試了很長時間,但無法找到正確的書面。 –
數組與期望輸出之間的關係是什麼? 'id'爲'172.1.1.7','id爲'8爲'172.1.1.7'的父節點是什麼?編輯:你怎麼得到這個輸入? – FirstOne