按值对关联数组进行排序

3

数组中的每个元素,第二个值指向该元素本身的父级。例如,在第一个数组中,“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")
);

预期输出

房间 > 楼层 > 建筑物 > 区域 > 城市

房间1 > 楼层1 > 建筑物1 > 区域1 > 城市1

我的解决方案

$route = [];

foreach ($locations as $locationKey => $locationArray) {

    if (!isset($locationArray[1])) continue;

    $nextLocation = $locations[$locationArray[1]][0];
    $route[] = $nextLocation;
}

但是,如果没有给定数组索引,比如索引4,它将不会添加数组array("room", 0);

另外,我无法弄清如何在一个路由完成后拆分路由。

我得到的输出:

Array
(
[0] => Area
[1] => City
[2] => Building
[3] => Floor
[4] => Area1
[5] => City1
[6] => Floor1
[7] => Building1
)

你得到了什么输出? - nice_dev
查看我的输出更新。 - Ali Rasheed
我的意思是,根据预期的输出格式,你得到了什么输出? - nice_dev
你不能使用for循环来获得输出,你需要通过数据递归。 - nice_dev
1个回答

5
你可以这样做:
首先保存每个节点和根节点获取方法的字典:
$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;
}

Live example: 3v4l


啊哈!我没有想到那个。 - Ali Rasheed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接