Php 用于检测形成路径的节点顺序的算法

Php 用于检测形成路径的节点顺序的算法,php,Php,我的问题很简单,我会尝试用例子来解释。 我有一个数组(未排序),如下所示: 所以基本上节点有一个id,可以有一个目的地,它是另一个节点的id。目标可以为空。任何节点都不能具有相同的目标。 我正在寻找一种可以输出以下内容的算法: $paths = [[1, 2, 3], [4, 5]] 如您所见,在输出中,对形成路径的节点进行排序,以便将作为节点1的目的地的节点2放置在节点1之后 有什么帮助吗? 谢谢。既然我的问题没有答案,我会用我的想法来回答,以便结束它。但这不是一个很好的答案(对不起) 现在

我的问题很简单,我会尝试用例子来解释。 我有一个数组(未排序),如下所示:

所以基本上节点有一个id,可以有一个目的地,它是另一个节点的id。目标可以为空。任何节点都不能具有相同的目标。 我正在寻找一种可以输出以下内容的算法:

$paths = [[1, 2, 3], [4, 5]]
如您所见,在输出中,对形成路径的节点进行排序,以便将作为节点1的目的地的节点2放置在节点1之后

有什么帮助吗?
谢谢。

既然我的问题没有答案,我会用我的想法来回答,以便结束它。但这不是一个很好的答案(对不起)

现在$path包含了我想要的输出!
谢谢大家。

到目前为止,您都做了哪些尝试?你能和我们分享你的代码吗?一个节点可以成为多个节点的目的地吗?哦,我以为已经有一个算法可以做到这一点,但我不知道它的名字,因为我不懂数学。对不起,问得不好。
$paths = [[1, 2, 3], [4, 5]]
$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);
  }
}