初始:
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => a
[1] => c
)
[2] => Array
(
[0] => c
[1] => b
)
[3] => Array
(
[0] => d
[1] => e
)
)
结果:
Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
)
[1] => Array
(
[0] => d
[1] => e
)
)
初始数组的前三项彼此相关但最后一项不相关。我认为可以通过使用Floyd-Warshall Algoritm来解决。请帮我拿到结果。
答案 0 :(得分:1)
不知道什么是floyd-warshall algorhitm,并且不确定你的最佳需求,但我做到了这一点:
$array = array(
['a', 'b'],
['a', 'c'],
['c', 'b'],
['d', 'e']
);
$result = array();
foreach($array as $itemOriginal){ //passing every array from the original array
$passed = false;
foreach($result as &$itemResult){ //passing every array from the new array (empty in the start)
foreach($itemOriginal as $item){ //passing every item from original arrays
if(in_array($item, $itemResult)){ //checking if the item is in one of earlier passed array transfered into new array already
$itemResult = array_unique(array_merge($itemResult, $itemOriginal)); //merging items into new array if one of their items equals
$passed = true; //no need to check another item from the current original array
break;
}
}
if($passed == true) //no need to find any of original items in new array
break;
}
if($passed == false) //for case the none of checked original items are in new array
$result[] = $itemOriginal;
}
echo '<pre>';
print_r($result); //to check it
答案 1 :(得分:0)
$result = array();
foreach ($array as $item) {
// If we're just getting started, get started
if (count($result) === 0) {
$result[] = $item;
// Otherwise, look for merge opportunities
} else {
$merged = false;
// Loop existing items
foreach ($result as $k => $resultItem) {
// If there's a match, merge & break
if (count(array_intersect($resultItem, $item)) > 0) {
$result[$k] = array_merge($resultItem, $item);
$merged = true;
break;
}
}
// If no match was found, create a new element
if (!$merged) {
$result[] = $item;
}
}
}