Ali*_*eed 3 php arrays sorting associative-array
在数组的每个元素中,第二个值指向元素本身的父级。因此,例如在第一个数组中,“ City”是根元素,而“ Area”是第一个子元素,因为第二个“ Area”元素(1)指向“ City”的键。
样本数据
$locations = array(
3 => array("Building", 2),
2 => array("Area", 1),
0 => array("Floor", 3),
1 => array("City"),
4 => array("Room", 0),
13 => array("Building1", 12),
12 => array("Area1", 11),
14 => array("Room1", 10),
10 => array("Floor1", 13),
11 => array("City1")
);
Run Code Online (Sandbox Code Playgroud)
预期产量
Room > Floor > Building > Area > City
Room1 > Floor1 > Building1 > Area1 > City1
我的解决方案
$route = [];
foreach ($locations as $locationKey => $locationArray) {
if (!isset($locationArray[1])) continue;
$nextLocation = $locations[$locationArray[1]][0];
$route[] = $nextLocation;
}
Run Code Online (Sandbox Code Playgroud)
但是,它不会添加没有索引的数组,例如,索引4 array("room", 0);
另外,我无法弄清楚如果一条路线完成后如何分割路线
我得到的输出:
Array
(
[0] => Area
[1] => City
[2] => Building
[3] => Floor
[4] => Area1
[5] => City1
[6] => Floor1
[7] => Building1
)
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
首先保存字典,了解如何获取每个节点和根:
$dic = [];
$roots = [];
foreach($locations as $k => $e) {
if (count($e) == 2)
$dic[$e[1]] = $k;
else
$roots[] = $k;
}
Run Code Online (Sandbox Code Playgroud)
然后循环所有根目录并创建路径:
foreach($roots as $root) {
$path = [];
$node = $root;
while (isset($dic[$node])) {
$path[] = $locations[$node][0];
$node = $dic[$node];
}
$path[] = $locations[$node][0];
echo implode(",", array_reverse($path)) . PHP_EOL;
}
Run Code Online (Sandbox Code Playgroud)
直播示例:3v4l