2

我编写了以下代码以在 PHP 中获取数组并将它们“连接”在一起,就像在 MySQL 中使用 LEFT JOIN 一样。为了我的缘故,我使用 foreach 编写了函数,并将数组传入并返回了一个新数组……我觉得它非常易读,但我也知道它效率低下。

理想情况下,我希望这个函数可以处理每个数组超过 10,000 行,我怀疑这意味着:1)通过引用传递 $original(以节省内存),以及 2)使用 PHP 迭代数组函数之一而不是 foreach (以节省处理时间)。

通常我不会发布这类“测验”之类的问题,但我觉得这个问题的答案会让社区受益。(像这家伙:加入 2 多维数组

愿 1)最快和 2)最低内存消耗的答案获胜!:P

<?php

// Join Arrays on Keys (**updated with knittl's suggestion**)
function array_join($original, $merge, $on) {
    if (!is_array($on)) $on = array($on);
    foreach ($merge as $remove => $right) {
        foreach ($original as $index => $left) {
            foreach ($on as $from_key => $to_key) {
                if (!isset($original[$index][$from_key])
                    || !isset($right[$to_key])
                    || $original[$index][$from_key] != $right[$to_key])
                    continue 2;
            }
            $original[$index] = array_merge($left, $right);
            unset($merge[$remove]);
        }
    }
    return array_merge($original, $merge);
}

// Test Arrays
$data1 = array(
    array(
        'productId' => '822335',
        'dateHour' => '2011-11-17 06:00:00',
        'qtySold' => '200',
        'qtyCanceled' => '10',
    ),
    array(
        'productId' => '822335',
        'dateHour' => '2011-11-17 07:00:00',
        'qtySold' => '100',
        'qtyCanceled' => '20',
    ),
    array(
        'productId' => '822336',
        'dateHour' => '2011-11-17 06:00:00',
        'qtySold' => '0',
        'qtyCanceled' => '30',
    ),
    array(
        'productId' => '822336',
        'dateHour' => '2011-11-17 07:00:00',
        'qtySold' => '50',
        'qtyCanceled' => '40',
    ),
);

$data2 = array(
    array(
        'entity_id' => '822335',
        'dateHour' => '2011-11-17 06:00:00',
        'productInventory' => '300',
    ),
    array(
        'entity_id' => '822335',
        'dateHour' => '2011-11-17 07:00:00',
        'productInventory' => '200',
    ),
    array(
        'entity_id' => '822336',
        'dateHour' => '2011-11-17 06:00:00',
        'productInventory' => '100',
    ),
    array(
        'entity_id' => '822336',
        'dateHour' => '2011-11-17 07:00:00',
        'productInventory' => '50',
    ),
);

// Usage
$result = array_join($data1, $data2, array(
    'productId' => 'entity_id',
    'dateHour' => 'dateHour'
));
print_r($result);
4

1 回答 1

2

更好的?

function array_join($original, $merge, $on) {
    if (!is_array($on)) $on = array($on);
    foreach ($merge as $remove => $right) {
        foreach ($original as $index => $left) {
            foreach ($on as $from_key => $to_key) {
                if (!isset($original[$index][$from_key])
                || !isset($right[$to_key])
                || $original[$index][$from_key] != $right[$to_key])
                    continue 2;
            }
            $original[$index] = array_merge($left, $right);
            unset($merge[$remove]);
        }
    }
    return array_merge($original, $merge);
}
于 2012-08-01T17:34:00.257 回答