[英]PHP Array tree structure to DB tree structure
我在PHP中有一個數據結構,可以使用Telnet這樣連接到交換機:
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編寫函數代碼,有什么想法或建議嗎?
更新:這是我的書面代碼,但不能使用:
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
=> ...
...
用這個。
$arr = array('172.1.1.2' => array(
array('IP' => '172.1.1.1','PlatformBrand' => 'dlink'),
array('IP' => '172.1.1.5','PlatformBrand' => 'dlink'),
array('IP' => '172.1.1.7','PlatformBrand' => 'dlink'),
array('IP' => '172.1.1.8','PlatformBrand' => 'dlink')
),
'172.1.1.6' => array(
array('IP' => '172.1.1.10','PlatformBrand' => 'dlink')
),
'172.1.1.7' => array(
array('IP' => '172.1.1.11','PlatformBrand' => 'dlink'),
array('IP' => '172.1.1.14','PlatformBrand' => 'dlink')
),
);
$sn = $parent = $sort = 0;
$hdr = "id | ip | parent | sort\r\n";
$hdr .= "--------------------------------\r\n";
foreach($arr as $k => $v){
$sn++;
$hdr .= "$sn | $k | $parent | $sort \r\n";
$parent = $sn;
foreach($v as $t => $d){
$sn++;
$hdr .= "$sn | {$d['IP']} | $parent | $sort \r\n";
$sort++;
}
$parent = 0;
$sort = 0;
}
echo nl2br($hdr);
請記住,問題中的數組是輸出,因此在迭代之前必須將其重新格式化為PHP數組。
當然,如果要寫入數據庫,則不需要換行符"\\n\\r"
和nl2br
。 只需在循環中建立查詢並執行即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.