我有這樣一個數組:重組陣列樹形結構在PHP
$array = array(
array('id' => 'foo.bar'),
array('id' => 'foo'),
array('id' => 'foo.baz.bar'),
array('id' => 'foo.bar.bar'),
);
我可以split
的id
領域,讓他們爲路徑,然後我想將它們整理成一棵樹。 ..我想這:
$result = array();
foreach($array as $element) {
$path = explode('.', $element['id']);
$subtree = $result;
while(!empty($path)) {
$path_element = array_shift($path);
if(empty($path_element)) {
$subtree['data'] = $element;
} else {
if(!is_array($subtree[$path_element])) {
$subtree[$path_element] = array();
}
$subtree = $subtree[$path_element];
}
}
}
但我得到的是警告的負載和空$res
- 陣列。
PHP Notice: Undefined index: foo in tree.php on line 24
PHP Stack trace:
PHP 1. {main}() tree.php:0
PHP Notice: Undefined index: bar in tree.php on line 24
PHP Stack trace:
PHP 1. {main}() tree.php:0
PHP Notice: Undefined index: foo in tree.php on line 24
PHP Stack trace:
PHP 1. {main}() tree.php:0
PHP Notice: Undefined index: foo in tree.php on line 24
PHP Stack trace:
PHP 1. {main}() tree.php:0
PHP Notice: Undefined index: baz in tree.php on line 24
PHP Stack trace:
PHP 1. {main}() tree.php:0
PHP Notice: Undefined index: bar in tree.php on line 24
PHP Stack trace:
PHP 1. {main}() tree.php:0
PHP Notice: Undefined index: foo in tree.php on line 24
PHP Stack trace:
PHP 1. {main}() tree.php:0
PHP Notice: Undefined index: bar in tree.php on line 24
PHP Stack trace:
PHP 1. {main}() tree.php:0
PHP Notice: Undefined index: bar in tree.php on line 24
PHP Stack trace:
PHP 1. {main}() tree.php:0
(第24行是$s = $s[$pe];
)
任何暗示?
EDIT:我的期望的輸出會是這樣
$res = array(
'foo' => array(
'data' => ...
'bar' => array(
'data' => ...
'bar' => array(
'data' => ...
),
),
'baz' => array(
'bar' => array(
'data' => ...
),
),
),
);
的data
元素是從陣列的原始元素。
你有一個例子樹如何看起來像? – Benz
你沒有把任何東西放在$ res中,難怪它是空的。另外,我甚至不知道它應該做什麼。 – enrey
@Benz增加了一個例子。 – Lanbo