更有效的合并两个数组的方法

时间:2016-07-30 14:28:40

标签: php arrays

我将数组的每个元素与数组的每个其他元素进行比较,如果两个元素具有相同的源/目标,则目标/源我将内部数组与员工合并,例如。

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

2 个答案:

答案 0 :(得分: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 :(得分: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