我不能得到这个代码的工作:PHP合并两个数组并保持键
$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使用json_encode,或者更好的办法,如果你知道一个发送此树。
您能给什么是你想要做更详细?你的输出是没有意义的。 '04'从哪里来? –
对不起04是一个错误...我有一个路径数组,然后我在'/'上分割每个路径,因为我想得到一个目录树。 – user3475649
看到我的答案和演示 –