php - 排序实体依赖

标签 php algorithm

我有一些相互关联的实体。

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 
)

Demo on 3v4l.org

关于php - 排序实体依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54004930/

相关文章:

php - 从字符串的每个新行的开头删除空格

在同一页上有进程的 PHP 表单?

objective-c - Objective-C 数据结构的近似运行时间比较

python类属性更新问题

python - 从文件中读取特定的单词和值并将它们存储在字典中

algorithm - 存储100万个电话号码

php - 如何将多个查询作为数组运行

php - 纯 SQL 与 PHP While 循环更快地执行更新

php - $_SESSION 的最大大小是多少?

c++ - 在多个容器中存储指向对象的指针