如果依赖项是数组,如何重新排列数组项目移动依赖项?

时间:2015-11-18 07:19:21

标签: php arrays algorithm multidimensional-array

我有以下数组,其中每个项目可能(或可能不依赖)另一个项目:

$test = array(
    'c' => array(
        'depends' => array('b')
    ),
    'a' => array(),
    'b' => array(
        'depends' => array('a', 'd')
    ),
    'd' => array(
        'depends' => array('a')
    )
);

我想要输出结果

$test = array(
    'a' => array(),
    'd' => array(
        'depends' => array('a')
    ),
    'b' => array(
        'depends' => array('a', 'd')
    ),
    'c' => array(
        'depends' => array('b')
    )
);

此代码有问题类似于此问题“How can I rearrange array items moving dependencies on top?

但有不同的是,如果依赖有多个依赖函数,则array_multisort无法对其进行排序。

2 个答案:

答案 0 :(得分:1)

我想这就是你要找的,虽然你的问题很模糊:

<?php
$input = array(
    'c' => array(
        'depends' => array('b')
    ),
    'a' => array(),
    'b' => array(
        'depends' => array('a', 'd')
    ),
    'd' => array(
        'depends' => array('a')
    )
);

$output = array();

foreach ($input as $dependant=>$settings) {
    if (   is_array($settings) 
        && isset($settings['depends']) 
        && is_array($settings['depends'])) {
        foreach ($settings['depends'] as $dependent) {
            $output[$dependent]['dependent'][] = $dependant;
        }
    }
}

var_dump($output);

输出结果为:

array(3) {
  'b' =>
  array(1) {
    'dependent' =>
    array(1) {
      [0] =>
      string(1) "c"
    }
  }
  'a' =>
  array(1) {
    'dependent' =>
    array(2) {
      [0] =>
      string(1) "b"
      [1] =>
      string(1) "d"
    }
  }
  'd' =>
  array(1) {
    'dependent' =>
    array(1) {
      [0] =>
      string(1) "b"
    }
  }
}

答案 1 :(得分:0)

<?php

$test = array(
    'c' => array(
        'depends' => array('b')
    ),
    'a' => array(),
    'b' => array(
        'depends' => array('a', 'd')
    ),
    'd' => array(
        'depends' => array('a')
    )
);

$rearranged = array();
$test_left = $test;
do {
  $resolved = false; // Check for rounds without any move
  reset($test_left);
  while (list($key, $val) = each($test_left)) {
    $move = false;
    if (isset($val['depends']) && !empty($val['depends'])) {
      // Dependencies count must be not greater than rearranged array length
      $depends = count($val['depends']) <= count($rearranged);

      // All dependencies must be set in rearranged array already
      while ($depends && (list(, $dep_key) = each($val['depends']))) {
        if (!array_key_exists($dep_key, $rearranged)) {
          $depends = false;
        }
      }

      $move = $depends;
    } else {
      // Independent items moves to top
      $move = true;
    }

    if ($move) {
      $rearranged[$key] = $val;
      unset($test_left[$key]);
      $resolved = true;
    }
  }
}
while ($resolved && !empty($test_left));

if (empty($test_left)) {
  echo 'Success<pre>';
  print_r($rearranged);
  echo '</pre>';
} else {
  echo 'There are some unresolved dependencies';
}