php - 根据值对关联数组进行排序
问题描述
在数组的每个元素中,第二个值指向元素本身的父元素。例如,在第一个数组中,“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")
);
预期产出
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;
}
但是,它不会添加数组中没有给定索引的数组,例如索引 4array("room", 0);
另外,如果一条路线完成,我无法弄清楚如何拆分路线
我得到的输出:
Array
(
[0] => Area
[1] => City
[2] => Building
[3] => Floor
[4] => Area1
[5] => City1
[6] => Floor1
[7] => Building1
)
解决方案
你可以这样做:
首先保存字典以了解如何获取每个节点和根:
$dic = [];
$roots = [];
foreach($locations as $k => $e) {
if (count($e) == 2)
$dic[$e[1]] = $k;
else
$roots[] = $k;
}
然后循环所有根并创建路径:
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;
}
现场示例:3v4l
推荐阅读
- html - bootstrap withword 新闻集成
- git - 如何将 GitHub 存储库恢复为某个提交
- r - 如何使用每个向量的元素名称将多个向量组合成一个数据框(在 R 中)
- r - ggplot2 - 如何通过值而不是按字母顺序重新排列带有标签的堆积条形图数据点
- android - 无法加载 AppCompat ActionBar 并出现未知错误?
- xml - xslt:通过 id 递归合并元素
- asp.net - VS17 中的 Nuget 包显示警告标志且未下载
- dart - 有没有一种方法,使用 Firestorage,将集合转换为地图列表,而不需要 Streambuilder/widget?
- google-apps-script - 在 Google Docs 文件中获取 ListItem 的父级
- unity3d - Unity在C#中更改2个子对象中的文本