订购实体依存关系

时间:2019-01-02 10:45:42

标签: php algorithm

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

passport-local

Php表示形式:

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

我需要订购它们,以便依存关系排在第一位。这是我期望的结果:

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

我很天真,尽管我可以像这样简单地使用usort

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

但是:

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'));

如何订购我的实体?

1 个答案:

答案 0 :(得分:2)

这是做您想要的事情的一种方法。它使用递归函数列出每个实体的所有依赖关系(关系)。在处理每个实体的关系列表之前,先对其进行排序,以便按字母顺序获取每个级别的关系的结果。最后,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 
)

Demo on 3v4l.org