我的问题很简单,我会尝试用例子来解释。 我有一个像这样的数组(未分类):
$nodes = [
['id' => 1, 'dest_id' => 2],
['id' => 2, 'dest_id' => 3],
['id' => 3, 'dest_id' => null],
['id' => 4, 'dest_id' => 5],
['id' => 5, 'dest_id' => null],
... etc
]
所以基本上节点有一个id,并且可以有一个目的地,它是另一个节点的id。目的地可以为空。没有节点可以具有相同的目的地。 我正在寻找一种可以输出这个的算法:
$paths = [[1, 2, 3], [4, 5]]
如您所见,在输出中,形成路径的节点是有序的,因此节点1的目的地节点2放在节点1之后。
有任何帮助吗? 谢谢。
答案 0 :(得分:0)
所以既然我的问题没有答案,我会用我想出的答案回答它,以便关闭它。但这不是一个很好的答案(抱歉)。
$raw_nodes = [
['id' => 1, 'dest_id' => 2],
['id' => 2, 'dest_id' => 3],
['id' => 3, 'dest_id' => null],
['id' => 4, 'dest_id' => 5],
['id' => 5, 'dest_id' => null]
];
$nodes = [];
// get the nodes in such a way that you can access them from their id
foreach($raw_nodes as $raw_node) {
$nodes[$raw_node['id']] = [
"id" => $raw_node['id'],
"dest_id" => $raw_node['dest_id'],
"parent_id" => null
];
}
// find the parent to each node
foreach($nodes as $node) {
if ($node['dest_id'] && $nodes[$node['dest_id']]) {
$nodes[$node['dest_id']]['parent_id'] = $node['id'];
}
}
function buildPath($nodes, $node) {
$path = [];
if ($node['parent_id']) {
$path = buildPath($nodes, $nodes[$node['parent_id']]);
}
array_push($path, $node['id']);
return $path;
}
$paths = [];
// for every node without a destination,
// build its full path by recursive search starting from its own parent
foreach($nodes as $node) {
if ($node['dest_id'] === null) {
$path = buildPath($nodes, $node);
array_push($paths, $path);
}
}
现在$ paths包含我想要的输出! 谢谢大家。