我有一个像这样的数组:
$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
-Array。
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];
)
有什么提示吗?
编辑:我想要的输出是这样的
$res = array(
'foo' => array(
'data' => ...
'bar' => array(
'data' => ...
'bar' => array(
'data' => ...
),
),
'baz' => array(
'bar' => array(
'data' => ...
),
),
),
);
data
元素是数组中的原始元素。