2016-03-07 27 views
0

我有陣列這樣再加上具有相同的值的陣列

$arr=[["a","b"],["b","c"],["d","e"],["f","c"]]; 

如果子陣列共享相同的值就應該被合併到一個陣列

預期輸出:

$arr=[["a","b","c","f"],["d","e"]]; 

我爲了解決這個問題,我試圖避免在foreach內部使用foreach。

+0

A)向我們展示一些代碼。 B)這是每個鍵或每個鍵=>值對嗎? –

+1

嘗試遞歸而不是迭代。考慮像'$ arr = [[「a」,「b」],[「d」,「e」],[「f」,「g」],[「b」,「c」],[ 「d」,「c」]];' –

+0

您的預期輸出沒有意義嗎? –

回答

0

這是我現在得到的解決方案。

$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); 
} 
0

以下算法應該做你想做的。它只是簡單地通過每一個項目和檢查檢查,如果它已經在新創建的數組中存在,如果這樣做,將其添加到該項目,而不是一個新問題:

<?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 
     ) 

) 

DEMO

+0

謝謝,但正如我所說我試圖避免嵌套循環。 –

+0

@AlexKneller有什麼特別的原因?你處理了多少物品? – h2ooooooo

1

看來你的內部數組總是有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)

指針是你的朋友。使用它們:)