【问题标题】:Extract "path" from array从数组中提取“路径”
【发布时间】:2021-08-14 14:14:18
【问题描述】:

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

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

【问题讨论】:

  • "我已经尝试了一些函数链",请告诉我们你的尝试!
  • 这能回答你的问题吗? PHP function to get recursive path keys with path
  • @0stone0 不是真的,它忽略了第一级“用户”和“产品”并包括数字键,我看看我是否可以调整它。这与我自己的努力非常相似

标签: php arrays api


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-02-20
    • 1970-01-01
    • 2014-03-26
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    相关资源
    最近更新 更多