首页 > 解决方案 > 从数组中提取“路径”

问题描述

我正在编写 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"]
];

请注意,数字键将被忽略,层次结构中仅包含命名键。我已经用谷歌搜索并试图找到可以做到这一点的东西,但我已经空白了。我已经尝试了一些函数链接,但我无法将我的头绕在循环上并正确返回。任何帮助表示赞赏!

标签: phparraysapi

解决方案


好的,在@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
)

推荐阅读