php - PHP索引数组到嵌套关联数组
问题描述
我需要根据特定规则将简单数组转换为嵌套数组。我已经实现了,但我正在寻找更好的解决方案。
简单的:
array(4) {
[0]=>
array(2) {
["id"]=>
string(2) "11"
["type"]=>
int(3)
}
[1]=>
array(2) {
["id"]=>
string(2) "10"
["type"]=>
int(2)
}
[2]=>
array(2) {
["id"]=>
string(1) "1"
["type"]=>
int(1)
}
[3]=>
array(2) {
["id"]=>
string(1) "0"
["type"]=>
int(1)
}
}
预期效果:
array(1) {
[0]=>
array(2) {
["type"]=>
int(1)
["child"]=>
array(1) {
[1]=>
array(2) {
["type"]=>
int(1)
["child"]=>
array(1) {
[10]=>
array(2) {
["type"]=>
int(2)
["child"]=>
array(1) {
[11]=>
array(2) {
["type"]=>
int(3)
["child"]=>
array(0) {
}
}
}
}
}
}
}
}
}
我的解决方案(不是很满意):
$nestedArray = [];
foreach ($simpleArray as $item)
{
if (!empty($nestedArray))
{
$array = $nestedArray;
reset($array);
$firstKey = key($array);
}
$nestedArray[$item['id']]['child'] = $nestedArray;
$nestedArray[$item['id']]['type'] = $item['type'];
if (!empty($firstKey))
{
unset($nestedArray[$firstKey]);
}
}
正如我所说,我正在寻找更优雅的方式来实现这一目标。规则非常简单:每个下一个项目都是前一个的孩子。
解决方案
你可以使用递归:
function nest($arr) {
return count($arr) ? ["type" => array_pop($arr)["type"], "child" => nest($arr)] : [];
}
使用您的示例输入,它看起来像这样:
$simpleArray = [
["id" => "11", "type" => 3],
["id" => "10", "type" => 2],
["id" => "1", "type" => 1],
["id" => "0", "type" => 1]
];
function nest($arr) {
return count($arr) ? ["type" => array_pop($arr)["type"], "child" => nest($arr)] : [];
}
$nested = nest($simpleArray));
$nested
将具有以下值:
[
"type" => 1,
"child" => [
"type" => 1,
"child" => [
"type" => 2,
"child" => [
"type" => 3,
"child" => []
]
]
]
]
推荐阅读
- excel - 从 Excel 写入 Word 文档时出错
- c# - 如何使用复选框来获取真值或假值?
- javascript - yt api、jquery 和分页 - 奇怪的行为
- python-3.x - 在 python 图中绘制日期
- html - 通过 Angular 中的按钮填充输入字段
- java - 有没有一种好方法可以最大限度地减少 Google Maps Roads API 的负载?
- elasticsearch - 在 Elasticsearch 中实现模糊前缀全文匹配查询
- sql - 一张表的 SQL 条件联合
- sql - 对 SQL 中的类似对象使用相同的表?
- c - SDL 可以在 Atari Mint 上运行吗?