简体   繁体   中英

Sorting an array based on class inheritance structure in PHP

I have an array that contains class names and and their base class . The structure looks like this:

$list[0] = array("class"=>"ckEditor", "base"=>"domTextArea");
$list[1] = array("class"=>"ComboBox", "base"=>"Control");
$list[2] = array("class"=>"Control", "base"=>"");
$list[3] = array("class"=>"domTextArea", "base"=>"Control");
..
... so on up to 50 classes

The problem is that the array is not sorted in terms of the inheritance structure. In this case The Control class must be on top. Is there any function in PHP that can sort this structure based on parent child relationship. The resulting array must look like this:

$list[0] = array("class"=>"Control", "base"=>"");
$list[1] = array("class"=>"domTextArea", "base"=>"Control");
$list[2] = array("class"=>"ckEditor", "base"=>"domTextArea");
$list[3] = array("class"=>"ComboBox", "base"=>"Control");

EDIT : It will also be helpful if anyone can suggest an algorithm to sort this type of sturcture.

You can just use recursive function.

$list[0] = array("class"=>"ckEditor", "base"=>"domTextArea");
$list[1] = array("class"=>"ComboBox", "base"=>"Control");
$list[2] = array("class"=>"Control", "base"=>"");
$list[3] = array("class"=>"domTextArea", "base"=>"Control");

$parents = array();
foreach($list as $item) {
    if (!is_array($parents[$item['base']])) {
        $parents[$item['base']] = array();
    }
    $parents[$item['base']][] = $item['class'];
}

function calculateChilds($base, $parents) {
    $result = array();
    if (is_array($parents[$base])) {
        foreach($parents[$base] as $child) {
            $result[] = array('base' => $base, 'class' => $child);
            $result = array_merge($result, calculateChilds($child, $parents));
        }
    }
    return $result;
}

var_dump(calculateChilds('', $parents));

Thils will output follows:

array(4) {
  [0]=>
  array(2) {
    ["base"]=>
    string(0) ""
    ["class"]=>
    string(7) "Control"
  }
  [1]=>
  array(2) {
    ["base"]=>
    string(7) "Control"
    ["class"]=>
    string(8) "ComboBox"
  }
  [2]=>
  array(2) {
    ["base"]=>
    string(7) "Control"
    ["class"]=>
    string(11) "domTextArea"
  }
  [3]=>
  array(2) {
    ["base"]=>
    string(11) "domTextArea"
    ["class"]=>
    string(8) "ckEditor"
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM