简体   繁体   English

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

[英]PHP merge two arrays based on combination of values

I have below two arrays:我有以下两个数组:

$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'
    }
}

I want to create a third array where in the combination of code and name matches, like this:我想创建第三个数组,其中代码和名称的组合匹配,如下所示:

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

I don't want the second array of $b to be considered since the combination of code and name in that does not match with the one in array $a Please help!我不想第二阵列$b ,因为在代码和名称的组合被认为与一个数组不匹配$a请帮助!

Your data structures are not built well for the required comparison.您的数据结构没有很好地构建用于所需的比较。 It would be easier if both of the arrays had "compound keys" instead of indexes.如果两个数组都有“复合键”而不是索引会更容易。 I mean, if the rows in the arrays looked like '123_ABC' => ['code' => '123', 'name' => 'ABC',] then making direct key-based comparisons would be a breeze.我的意思是,如果数组中的行看起来像'123_ABC' => ['code' => '123', 'name' => 'ABC',]那么进行基于键的直接比较将是轻而易举的。

Using what you have and with the intention of reducing the total iterations over the arrays, I recommend nested loops with early breaks in the inner loop as soon as a match is found.使用您所拥有的并为了减少数组的总迭代次数,我建议在找到匹配项后立即在内部循环中提前中断的嵌套循环。

Code: ( 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);

Output:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM