PHP多维数组删除部分重复项

时间:2014-04-19 15:33:00

标签: php arrays algorithm sorting

我有一个包含此

的数组
Array ( 
[0] => Array ( [0] => Sub1 ) 
[1] => Array ( [0] => Sub1 [1] => Gold ) 
[2] => Array ( [0] => Sub1 [1] => Sub2 ) 
[3] => Array ( [0] => Sub1 [1] => Sub2 [2] => Sub3 ) 
[4] => Array ( [0] => Sub1 [1] => Sub2 [2] => Sub3 [3] => Sub4 ) 
[5] => Array ( [0] => Sub1 [1] => Test ) 
)

如何删除[4]

中存在的数组[2] [3]

,数组就像

Array (  
[0] => Array ( [0] => Sub1 [1] => Gold )  
[1] => Array ( [0] => Sub1 [1] => Sub2 [2] => Sub3 [3] => Sub4 ) 
[2] => Array ( [0] => Sub1 [1] => Test ) 
)

是否可以自动化?

1 个答案:

答案 0 :(得分:2)

$result = array();
foreach ($original as $orig_el) {
    $found = false;
    foreach ($result as &$new_el) {
        if (count($orig_el) >= count($new_el) && array_slice($orig_el, 0, count($new_el)) == $new_el) {
            $new_el = $orig_el;
            $found = true;
            break;
        }
    }
    if (!$found) {
        $result[] = $orig_el;
    }
}