对实体依赖项进行排序



我有一些彼此相关的实体。

Answer
  - AnswerGroup
AnswerGroup
Condition
  - Question
Notion
Question
  - AnswerGroup
  - Theme
  - Notion
Theme

PHP 表示:

$entities = [
    ['name' => 'Answer', 'relations' => ['AnswerGroup']],
    ['name' => 'AnswerGroup', 'relations' => []],
    ['name' => 'Condition', 'relations' => ['Question']],
    ['name' => 'Notion', 'relations' => []],
    ['name' => 'Question', 'relations' => ['Theme', 'AnswerGroup', 'Notion']],
    ['name' => 'Theme', 'relations' => []],
];

我需要对它们进行排序,以便首先使用依赖项。这是我期待的结果:

array:6 [
  0 => "AnswerGroup"
  1 => "Answer"
  2 => "Notion"
  3 => "Theme"
  4 => "Question"
  5 => "Condition"
]

我天真地认为我可以简单地使用这样的usort

usort($entities, function ($entityA, $entityB) {
    if (in_array($entityB, $entityA['relations'])) {
        return 1;
    }
    if (in_array($entityA, $entityB['relations'])) {
        return -1;
    }
    return 0;
});

但:

dump(array_column($entities ,'name'));

array:6 [
  0 => "Answer"
  1 => "AnswerGroup"
  2 => "Condition"
  3 => "Notion"
  4 => "Question"
  5 => "Theme"
]

如何订购我的实体?

这是做你想做的事的一种方式。它使用递归函数列出每个实体的所有依赖关系(关系)。每个实体的关系列表在处理之前进行排序,以获得每个级别关系的字母顺序结果。最后array_unique用于去除重复的条目(例如 AnswerGroupAnswerQuestion的关系)。

function list_dependents($entity, $entities) {
    $sorted = array();
    sort($entity['relations']);
    foreach ($entity['relations'] as $r) {
        $sorted = array_merge($sorted, list_dependents($entities[array_search($r, array_column($entities, 'name'))], $entities));
    }
    $sorted = array_merge($sorted, array($entity['name']));
    return $sorted;
}
$sorted = array();
foreach ($entities as $entity) {
    $sorted = array_merge($sorted, list_dependents($entity, $entities));
}
$sorted = array_values(array_unique($sorted));
print_r($sorted);

输出:

Array (
    [0] => AnswerGroup
    [1] => Answer
    [2] => Notion
    [3] => Theme
    [4] => Question
    [5] => Condition 
)

3v4l.org 演示

最新更新