PHP Order数组基于元素依赖

PHP Order数组基于元素依赖

问题描述:

Fairly hard one to explain, but effectively I've got an array of items which have IDs, of which can contain a list of IDs for other array items. for example

$items = [
   [id: 'one', deps: ['three']],
   [id: 'two'],
   [id: 'three', deps: ['four', 'two']],
   [id: 'four']
];

So as you can see here, one depends on three, and three depends on four and two.

I need to get a new array, that contains these items in order - so that the dependencies are listed in order. So the above array would convert into

$items = [
   [id: 'four'],
   [id: 'two'],
   [id: 'three', deps: ['four', 'two']],
   [id: 'one', deps: ['three']]
];

How would I complete this? I've tried various while loops checking for item positions, but can't crack it.

Thanks

UPDATE Some people have said its a duplicate question of THIS but the main difference being the above example has multiple dependencies - whereas the mentioned thread only works on a single string dependency

相当难以解释,但实际上我有一系列具有ID的项目,其中包含 其他数组项的ID列表。 例如 p>

  $ items = [
 [id:'one',deps:['three']],
 [id:'two'],
  [id:'three',deps:['four','two']],
 [id:'four'] 
]; 
  code>  pre> 
 
 

正如你在这里看到的,一个取决于三个,三个取决于四个和两个。 p>

我需要得到一个新的数组,它按顺序包含这些项 - 以便依赖 按顺序列出。 所以上面的数组将转换为 p>

  $ items = [
 [id:'four'],
 [id:'two'],
 [id:  'three',deps:['four','two']],
 [id:'one',deps:['three']] 
]; 
  code>  pre> 
  
 

我将如何完成此操作? 我已尝试各种while循环检查项目位置,但无法破解它。 p>

谢谢 p>

更新 strong> 有些人说它有一个重复的问题这个 a>但主要区别在于上面的示例有多个依赖项 - 而提到的线程仅适用于单个字符串依赖项 p> div>

you can use a function like this, that iterates until all dependencies are met, or no more dependencies can be resolved:

$items = array(array('id' => 'one', 'deps' => array('three')),
                array('id' => 'two'),
                array('id' => 'three', 'deps' => array('four', 'two')),
                array('id' =>'four'));


$sortedItems = sortDeps($items);
var_dump($sortedItems);

function sortDeps($items) {
    $res = array();
    $doneList = array();

    // while not all items are resolved:
    while(count($items) > count($res)) {
        $doneSomething = false;

        foreach($items as $itemIndex => $item) {
            if(isset($doneList[$item['id']])) {
                // item already in resultset
                continue;
            }
            $resolved = true;

            if(isset($item['deps'])) {
                foreach($item['deps'] as $dep) {
                    if(!isset($doneList[$dep])) {
                        // there is a dependency that is not met:
                        $resolved = false;
                        break;
                    }
                }
            }
            if($resolved) {
                //all dependencies are met:
                $doneList[$item['id']] = true;
                $res[] = $item;
                $doneSomething = true;
            }
        }
        if(!$doneSomething) {
            echo 'unresolvable dependency';
        }
    }
    return $res;
}