我有阵列这样再加上具有相同的值的阵列
$arr=[["a","b"],["b","c"],["d","e"],["f","c"]];
如果子阵列共享相同的值就应该被合并到一个阵列
预期输出:
$arr=[["a","b","c","f"],["d","e"]];
我为了解决这个问题,我试图避免在foreach内部使用foreach。
我有阵列这样再加上具有相同的值的阵列
$arr=[["a","b"],["b","c"],["d","e"],["f","c"]];
如果子阵列共享相同的值就应该被合并到一个阵列
预期输出:
$arr=[["a","b","c","f"],["d","e"]];
我为了解决这个问题,我试图避免在foreach内部使用foreach。
这是我现在得到的解决方案。
$arr=[["a","b","c","f"],["d","e"]];
$sortedArray = sortFunction($arr,0,array());
function sortFunction($old,$index,$new) {
if ($index == sizeof($old)) return $new;
for ($i = 0; $i<sizeof($new); $i++) {
if (count(array_intersect($new[$i],$old[$index]))) {
$new[$i] = array_unique(array_merge($old[$index],$new[$i]), SORT_REGULAR);
return sortFunction($old,$index + 1,$new);
}
}
$new[] = $old[$index];
return sortFunction($old,$index + 1,$new);
}
以下算法应该做你想做的。它只是简单地通过每一个项目和检查检查,如果它已经在新创建的数组中存在,如果这样做,将其添加到该项目,而不是一个新问题:
<?php
$arr=[["a","b"],["b","c"],["d","e"],["f","c"]];
$newArr = [];
foreach ($arr as $items) {
$newKey = null;
foreach ($items as $item) {
foreach ($newArr as $newItemsKey => $newItems) {
if (in_array($item, $newItems)) {
$newKey = $newItemsKey;
break 2;
}
}
}
if ($newKey !== null) {
$newArr[$newKey] = array_merge($newArr[$newKey], $items);
} else {
$newArr[] = $items;
}
}
$newArr = array_map('array_unique', $newArr);
print_r($newArr);
输出:
Array
(
[0] => Array
(
[0] => a
[1] => b
[3] => c
[4] => f
)
[1] => Array
(
[0] => d
[1] => e
)
)
谢谢,但正如我所说我试图避免嵌套循环。 –
@AlexKneller有什么特别的原因?你处理了多少物品? – h2ooooooo
看来你的内部数组总是有2个项目。所以嵌套循环是没有必要的。下面是我最初在JS写了一个解决方案,但它应该工作一样的好,最有效在PHP中:
$arr=[["a","b"],["b","c"],["d","e"],["f","c"],["h","e"]];
$output = [];
$outputKeys = [];
$counter = 0;
foreach($arr as $V) {
if(!isset($outputKeys[$V[0]]) && !isset($outputKeys[$V[1]])) {
$output[$counter] = [$V[0], $V[1]];
$outputKeys[$V[0]] = &$output[$counter];
$outputKeys[$V[1]] = &$output[$counter];
$counter++;
}
elseif(isset($outputKeys[$V[0]]) && !isset($outputKeys[$V[1]])) {
array_push($outputKeys[$V[0]], $V[1]);
$outputKeys[$V[1]] = &$outputKeys[$V[0]];
}
elseif(!isset($outputKeys[$V[0]]) && isset($outputKeys[$V[1]])) {
array_push($outputKeys[$V[1]], $V[0]);
$outputKeys[$V[0]] = &$outputKeys[$V[1]];
}
}
var_dump($output); // [["a","b","c","f"],["d","e","h"]]
DEMO (click the execute button)
指针是你的朋友。使用它们:)
A)向我们展示一些代码。 B)这是每个键或每个键=>值对吗? –
尝试递归而不是迭代。考虑像'$ arr = [[“a”,“b”],[“d”,“e”],[“f”,“g”],[“b”,“c”],[ “d”,“c”]];' –
您的预期输出没有意义吗? –