PHP-从数组创建路径列表

时间:2019-03-20 21:10:00

标签: php arrays tree

我有一个ID数组,这些ID形成一个树形结构,用于存储类型的应用程序。

Array image

然后显示类似于此的树形结构

enter image description here

我想要做的是创建每个数组元素的完整路径的列表。

[366 =>'文件',356 =>'其他',354 =>'照片',368 ='照片/城市',375 ='照片/城市/英国',376 ='照片/城市/苏格兰']

菜单是用户定义的,因此这只是一个示例,它可以具有更多的级别。

每个数组元素的名称都是从名称数组中添加的,即名称[376](照片)

我已经尝试了几种递归函数并且很挣扎,希望有人比我更擅长PHP! 谢谢

2 个答案:

答案 0 :(得分:1)

希望我能理解您想要实现的目标。在这种情况下,这可能是一个解决方案

<?php

$ids = [
  354 => [
    368 => [
      375,
      376
    ]
  ],
  356,
  366
];

$names = [
    354 => "Photos", 
    368 => "Cities",
    375 => "England",
    376 => "Scotland",
    356 => "Files",
    366 => "Misc"
];


print_r(build_list($ids));

function build_list($ids, $path = ""){
  global $names;
  $list = [];
  foreach($ids as $key => $value){
    if(is_array($value)){
      //$list[$key] = $path . $names[$key]; // uncomment if you need output (2)
      $list = array_replace_recursive($list, build_list($value, ($path . $names[$key] . "/")))
    }else{
      $list[$value] = $path . $names[$value];
    }
  }
  return $list;
}

?>

输出(1)

Array
(
  [375] => Photos/Cities/England
  [376] => Photos/Cities/Scotland
  [356] => Files
  [366] => Misc
)

输出(2)

Array
(
  [354] => Photos
  [368] => Photos/Cities
  [375] => Photos/Cities/England
  [376] => Photos/Cities/Scotland
  [356] => Files
  [366] => Misc
)

答案 1 :(得分:1)

此功能将执行您想要的操作。它递归地遍历树,为每个键创建元素,并在递归中向下传递前缀以创建每个元素的名称:

function make_paths($array, $names, $prefix = '') {
    $output = array();
    foreach ($array as $key => $arr) {
        $name = $prefix . ($prefix != '' ? '/' : '') . $names[$key];
        if (count($arr)) {
            $output = $output + make_paths($arr, $names, $name);
        }
        $output[$key] = $name;
    }
    return $output;
}

输出:

Array (
    [375] => Photos/Cities/England
    [376] => Photos/Cities/Scotland
    [368] => Photos/Cities
    [354] => Photos
    [356] => Misc
    [366] => Files 
)

Demo on 3v4l.org