【发布时间】:2020-02-04 15:36:17
【问题描述】:
我需要一个数组,将每个元素的键(由/ 拆分)转换为子数组,并在新数组中以正确的格式分配数据。
可以有多层嵌套,实际上永远不会超过 10 层,但这是有待决定的。
例如; 给定的输入
$i_have_this = [
"Base/child" => [
[
"filename" => "child-1",
"last_modified" => "29/01/2020"
],
[
"filename" => "child-2",
"last_modified" => "29/01/2020"
],
[
"filename" => "child-3",
"last_modified" => "29/01/2020"
]
],
"Base/child/grandChild1" => [
[
"filename" => "grandChild1-1",
"last_modified" => "29/01/2020"
]
],
"Base/child/grandChild2" => [
[
"filename" => "grandChild2-1",
"last_modified" => "29/01/2020"
],
[
"filename" => "grandChild2-2",
"last_modified" => "29/01/2020"
],
[
"filename" => "grandChild2-3",
"last_modified" => "29/01/2020"
],
[
"filename" => "grandChild2-4",
"last_modified" => "29/01/2020"
],
[
"filename" => "grandChild2-5",
"last_modified" => "29/01/2020"
]
]
];
我想要输出
$want_this = [
'name' => 'Base',
'children' => [
[
'name' => 'child',
'children' => [
["name" => "child-1"],
["name" => "child-2"],
["name" => "child-3"],
[
"name" => "grandChild1",
"children" => [
["name" => "grandChild1-1"]
]
],
[
"name" => "grandChild2",
"children" => [
["name" => "grandChild2-1"],
["name" => "grandChild2-2"],
["name" => "grandChild2-3"],
["name" => "grandChild2-4"]
]
],
]
]
]
];
到目前为止我有;
foreach($i_have_this as $path => $value) {
$temp = &$want_this;
foreach (explode('/', $path) as $key) {
$temp = &$temp[$key];
}
$temp = $value;
}
但不能完全完成。
【问题讨论】:
-
您会遇到问题,因为在 PHP 中您不允许重复键。相反,您必须将它们编号为 name1、name2 等或具有不同的结构。你能更新你的问题吗?
-
没有重复的键,它们都在自己的数组中
-
我没有时间给出完整的答案,但也许可以考虑使用调用自身的递归函数。当您不确切知道需要多少级别时,它会很有帮助。不确定这是否会对您有帮助,但可能指向正确的方向。
标签: php arrays multidimensional-array