我希望使用Tree
PHP
结构格式化数组
TITLE 1
-- SUB TITLE 1-1
---- SUB TITLE 1-2
TITLE 2
-- SUB TITLE 2-1
Array
结构:
Array
(
[0] => Array
(
[id] => 1
[sub_id] => 1
[title] => TITLE 1
[url] => www.title1.com
)
[1] => Array
(
[id] => 4
[sub_id] => 4
[title] => TITLE 2
[url] => www.title2.com
)
[2] => Array
(
[id] => 2
[sub_id] => 1
[title] => SUB TITLE 1-1
[url] => www.subtitle1.com
)
[3] => Array
(
[id] => 3
[sub_id] => 2
[title] => SUB TITLE 1-2
[url] => www.subtitle2.com
)
[4] => Array
(
[id] => 5
[sub_id] => 4
[title] => SUB TITLE 2-1
[url] => www.subtitle2.com
)
)
我不知道应该怎么做。
答案 0 :(得分:2)
这是你的解决方案:
<?php
$data=Array
(
0 => Array
(
'id' => 1,
'sub_id' => 1,
'title' => 'TITLE 1',
'url' => 'www.title1.com',
),
1 => Array
(
'id' => 4,
'sub_id' => 4,
'title' => 'TITLE 2',
'url' => 'www.title2.com',
),
2 => Array
(
'id' => 2,
'sub_id' => 1,
'title' => 'SUB TITLE 1-1',
'url' => 'www.subtitle1.com',
),
3 => Array
(
'id' => 3,
'sub_id' => 2,
'title' => 'SUB TITLE 1-2',
'url' => 'www.subtitle2.com',
),
4 => Array
(
'id' => 5,
'sub_id' => 4,
'title' => 'SUB TITLE 2-1',
'url' => 'www.subtitle2.com',
),
);
function find_index(&$arr, $ind){
if(empty($arr))
return false;
else {
foreach($arr as &$aa){
if($aa['id']==$ind['sub_id']) {
$key=count($aa['sub_ar']);
$aa['sub_ar'][$key]=$ind;
$aa['sub_ar'][$key]['sub_ar']=array();
return true;
}
else{
$res=find_index($aa['sub_ar'],$ind);
if($res)
return true;
}
}
return false;
}
}
$res=array();
foreach($data as $key=>$dat){
if($dat['sub_id']==$dat['id']){
$res[$key]=$dat;
$res[$key]['sub_ar']=array();
}
else {
$ret=find_index($res,$dat);
}
}
?>
<pre><?php print_r($res); ?></pre>