PHP根据值的组合合并两个数组

时间:2019-02-07 08:16:01

标签: php arrays multidimensional-array

我有以下两个数组:

$a = Array {
    [0] => Array {
        [code] => '123',
        [name] => 'ABC'
    },
    [1] => Array {
        [code] => '456',
        [name] => 'XYZ'
    }
}

$b = Array {
    [0] => Array {
        [code] => '123',
        [name] => 'ABC',
        [price] => '34'
    },
    [1] => Array {
        [code] => '456',
        [name] => 'PQR',
        [price] => '56'
    },
    [2] => Array {
        [code] => '456',
        [name] => 'XYZ',
        [price] => '90'
    }
}

我想创建第三个数组,其中的代码和名称匹配,如下所示:

$c = Array {
    [0] => Array {
        [code] => '123',
        [name] => 'ABC',
        [price] => '34'
    },
    [1] => Array {
        [code] => '456',
        [name] => 'XYZ',
        [price] => '90'
    }
}

我不希望考虑$b的第二个数组,因为其中的代码和名称的组合与数组$a的不匹配 请帮忙!

2 个答案:

答案 0 :(得分:1)

您的数据结构不能很好地进行所需的比较。如果两个数组都具有“复合键”而不是索引,则会更容易。我的意思是,如果数组中的行看起来像'123_ABC' => ['code' => '123', 'name' => 'ABC',],那么直接进行基于键的比较将很容易。

使用现有功能并减少数组的总迭代次数,建议在找到匹配项后立即在内部循环中使用带有早期中断的嵌套循环。

代码:(Demo

$whiteList = [
    ['code' => '123', 'name' => 'ABC',],
    ['code' => '456', 'name' => 'XYZ',],
];

$pricedList = [
    ['code' => '123', 'name' => 'ABC', 'price' => '34'],
    ['code' => '456', 'name' => 'PQR', 'price' => '56'],
    ['code' => '456', 'name' => 'XYZ', 'price' => '90'],
    ['code' => '456', 'name' => 'GHI', 'price' => '70'],
];

$result = [];
foreach ($whiteList as $whiteRow) {
    foreach ($pricedList as $pricedRow) {
        if ($whiteRow['code'] === $pricedRow['code'] && $whiteRow['name'] === $pricedRow['name']) {
            $result[] = $pricedRow;
            continue 2;  // no reason to keep iterating inner loop after match is found
        }
    }
}
var_export($result);

输出:

array (
  0 => 
  array (
    'code' => '123',
    'name' => 'ABC',
    'price' => '34',
  ),
  1 => 
  array (
    'code' => '456',
    'name' => 'XYZ',
    'price' => '90',
  ),
)

答案 1 :(得分:0)

您可以按以下方式使用array_merge和array_reduce来实现

$temp = array_merge($a, $b);
$result = array_reduce($temp, function ($i, $j) {
    if (isset($i[$j['code']]) && isset($i[$j['name']])) {
        $i[$j['code']] = array_merge($i[$j['code']], $j);
    }else{
        $i[$j['code']] = $j;
    }
    return $i;
}, []);
print_r($result);

这是您的working demo