2016-07-30 4 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_search, array_keys, array_slice и array_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

Смежные вопросы