【发布时间】:2014-05-08 23:45:42
【问题描述】:
我无法让这段代码工作:
$paths = ['2014/','2014/04/','2015/'];
$tree = array();
foreach ($paths as $path) {
$dir_exploded = explode("/", $path);
array_pop($dir_exploded);
$tmp = array();
for ($i = count($dir_exploded) - 1; $i >= 0; $i--) {
if ($i == count($dir_exploded) - 1) {
$children = array();
} else {
$children = array($tmp);
}
$tmp = array('text' => $dir_exploded[$i], 'children' => $children);
}
$tree = array_replace_recursive($tree, $tmp);
}
echo(json_encode(array(array('text' => '/', 'children' => array($tree)))));
我明白了:
[
{
"text": "/",
"children": [
{
"text": "2015",
"children": [
{
"text": "04",
"children": []
}
]
}
]
}
]
所以 2014 已被这 2 个数组的合并删除。我想得到:
[
{
"text": "/",
"children": [
{
"text": "2014",
"children": [
{
"text": "04",
"children": []
}
]
},{
"text": "2015",
"children": []
}
]
}
]
至少我想使用 json_encode 以 json 格式发送这棵树,或者如果你知道一个更好的方法。
【问题讨论】:
-
您能否详细说明您要做什么?你的输出毫无意义。
04哪里来的? -
Sorry 04 是一个错误...我有一个路径数组,然后我在“/”上分割每个路径,因为我想得到一个目录树。
-
看我的回答和演示