2016-07-30 43 views
0

我比較陣列的每個元素與陣列的每個其他元素,如果兩個元素具有相同的源/目標,目標/源我合併內部陣列與員工例如更有效的方式合併兩個陣列

0=> source - 3 target - 4 officers => 0 - 'Aberdeen Asset Management PLC' 
1=> source - 3 target - 4 officers => 0 - 'whatever' 

將被合併到

0=> source - 3 target - 4 officers => 0 - 'Aberdeen Asset Management PLC', 1 - 'whatever' 

下面是數據看起來的樣子:

enter image description here

我的代碼是1000更多的行要經過真正的低效執行需要大約90秒,這是不可接受的。

foreach ($edges as $i => &$edge) { 
     for ($j = $i + 1; $j < count($edges); $j++) { 
      if ($edge['source'] == $edges[$j]['source'] && $edge['target'] == $edges[$j]['target']) { 
       foreach ($edges[$j]['officers'] as $officer) { 
        array_push($edge['officers'], $officer); 
       } 
       array_splice($edges, $j, 1); 
      } 
     } 
    } 

回答

1

我認爲你應該這樣做(更新):

// we will have new array with officers 
$new_items = array(); 
foreach ($edges as $edge) { 
    // create unique keys for `source-target` and `target-source` pairs 
    $source_target = $edge['source'] . ':' . $edge['target']; 
    $target_source = $edge['target'] . ':' . $edge['source']; 

    // check if unique keys exists in `new_items` 
    if (!isset($new_items[$source_target]) && !isset($new_items[$target_source])) { 
     // if unique key doesn't exist - create a new one 
     $new_items[$source_target] = $edge; 
    } elseif (isset($new_items[$source_target])) { 
     // if unique key exists `$source_target` - add an officer to it 
     $new_items[$source_target]['officers'][] = $edge['officers'][0]; 
    } else { 
     // if unique key exists `$target_source` - add an officer to it 
     $new_items[$target_source]['officers'][] = $edge['officers'][0]; 
    } 
} 

// for returning to numeric indexes use `array_values` 
$new_items = array_values($new_items); 
+1

你不能自己解決你的問題? –

+0

@u_mulder好了,如果他告訴你**他需要什麼,然後複製粘貼就會容易多了。畢竟,你這樣做是免費的,因爲你沒有什麼比做代碼更好的做法,所以其他人可以從中獲利,爲什麼不放縱所有願望呢? :) –

1

使用array_searcharray_keysarray_slicearray_merge功能的解決方案:

// an exemplary array 
$edges = [ 
    0 => ['source' => 3, 'target' => 4, 'officers' => ['Aberdeen Asset Management PLC']], 
    1 => ['source' => 3, 'target' => 4, 'officers' => ['whatever']], 
    3 => ['source' => 4, 'target' => 7, 'officers' => ['Jason']], 
    4 => ['source' => 4, 'target' => 5, 'officers' => ['John']], 
    5 => ['source' => 4, 'target' => 7, 'officers' => ['Bourne']] 
]; 

foreach ($edges as $k => &$v) { 
    $next_slice = array_slice($edges, array_search($k, array_keys($edges)) + 1); 
    foreach ($next_slice as $key => $item) { 
     if ($item['source'] == $v['source'] && $item['target'] == $v['target']) { 
      $v['officers'] = array_merge($v['officers'], $item['officers']); 
      unset($edges[$k + $key + 1]); 
     } 
    } 
} 

print_r($edges); 

DEMO link