php - 从数组中提取“路径”
问题描述
我正在编写 API 文档,因此我正在解析示例 XML/JSOn 输出,并且需要找到所有命名键来添加定义。所以,我有一个这样的数组:
$array = [
"user" => [
"name" => "John",
"email" => "email@email.com",
"products" => [
0 => "product A",
1 => "product B"
],
"files" => [
"logo" => "/path/logo.jpg",
"profile" => "/path/profile.jpg"
]
],
"offer" => [
0 => "My offer"
]
];
我想从数组中提取所有键,无论其深度如何,并获得类似于:
$keys = [
0 => ["user"],
1 => ["user", "name"],
2 => ["user", "email"],
3 => ["user", "products"],
4 => ["user", "files"],
5 => ["user", "files", "logo"],
6 => ["user", "files", "profile"],
7 => ["offer"]
];
请注意,数字键将被忽略,层次结构中仅包含命名键。我已经用谷歌搜索并试图找到可以做到这一点的东西,但我已经空白了。我已经尝试了一些函数链接,但我无法将我的头绕在循环上并正确返回。任何帮助表示赞赏!
解决方案
好的,在@0stone0 的帮助下,我被引导到一个 Stackoverflow 答案,这让我正确,这是最终功能:
function definitionTree(array $array): array{
$tree = function($siblings, $path) use (&$tree) {
$result = [];
foreach ($siblings as $key => $val) {
$currentPath = is_numeric($key) ? $path : array_merge($path, [$key]);
if (is_array($val)) {
if (!is_numeric($key)) $result[] = join(' / ', $currentPath);
$result = array_merge($result, $tree($val, $currentPath));
} else {
$result[] = join(' / ', $currentPath);
}
}
return $result;
};
$paths = $tree($array, []);
return array_unique($paths);
}
它返回以下内容:
Array
(
[0] => user
[1] => user / name
[2] => user / email
[3] => user / products
[6] => user / files
[7] => user / files / logo
[8] => user / files / profile
[9] => offer
)
推荐阅读
- angular - 卡片被放置在彼此的顶部,角度 10
- ios - ios Facebook inApp UserAgent中的手机号码代表什么?
- tabs - ASP.Net Core MVC 导航选项卡
- amazon-web-services - AWS Lambda:如果等待 Amazon S3 的 File 事件,Lambda 会产生费用吗
- r - 制作一个 ggplot 箱线图,其中每列都是它自己的箱线图
- python - 保存矩形时出现问题,它使我的游戏崩溃
- amazon-elastic-beanstalk - 在 AWS Elastic Beanstalk 中识别失败的命令挂钩
- javascript - 在绘制新图表之前清除 Anychart (Javascript) 容器
- android - Android 上的 RotationTransition 错误
- javascript - 有没有办法在html中触发事件