PHP - 根据第一个数组的键 属性 值组合两个数组 - 改进代码

PHP - Combine Two Arrays based on a key property value of the first array - improve code

下面有两个关联数组

第一个是当天的库存信息,这是存储在不同的数据库中。

第二个数组包含产品的信息,如名称、描述等。

我希望根据键属性值合并或组合两个数组(product_id ) 第一个数组.

到目前为止,我正在使用两个 foreach 循环将两者结合起来。 我怎样才能改进我的代码?

示例(常用键为product_id):

$array_one = [
    [
        'product_id' => 1,
        'product_stock' => '1.2',
        'stock_date' => '2022-02-15'
    ],
    [
        'product_id' => 2,
        'product_stock' => '5',
        'stock_date' => '2022-02-15'
    ],
];
$array_two = [
    [
        'product_id' => 1,
        'product_slug' => 'product_one',
        'product_description' => 'this is the product one'
    ],
    [
        'product_id' => 2,
        'product_slug' => 'product_two',
        'product_description' => 'this is the product two'
    ],
    [
        'product_id' => 3,
        'product_slug' => 'product_three',
        'product_description' => 'this is the product three'
    ],
];

到目前为止我得到了:

$new_array = [];

foreach ($array_one as $key => $value) {
    $new_array[ $value['product_id'] ] = $value ;
}
foreach ($array_two as $key => $value) {
    if ( isset( $new_array[ $value['product_id'] ] ) ) {
        $new_array[ $value['product_id'] ]['product_slug'] = $value['product_slug'];
        $new_array[ $value['product_id'] ]['product_description'] = $value['product_description'];
    }
}

结果符合预期:

array(2) {
  [1]=>
  array(5) {
    ["product_id"]=>
    int(1)
    ["product_stock"]=>
    string(3) "1.2"
    ["stock_date"]=>
    string(10) "2022-02-15"
    ["product_slug"]=>
    string(11) "product_one"
    ["product_description"]=>
    string(23) "this is the product one"
  }
  [2]=>
  array(5) {
    ["product_id"]=>
    int(2)
    ["product_stock"]=>
    string(1) "5"
    ["stock_date"]=>
    string(10) "2022-02-15"
    ["product_slug"]=>
    string(11) "product_two"
    ["product_description"]=>
    string(23) "this is the product two"
  }
}

首先修改您的第二个数组,以便它使用产品 ID 作为键 - 这使得与第一个数组中的产品 ID 对应的项目的 look-up 更容易。

$array_two = array_combine(array_column($array_two, 'product_id'), $array_two);
$new_array = [];
foreach($array_one as $product) {
    $product['product_slug'] = $array_two[$product['product_id']]['product_slug'];
    $product['product_description'] =
         $array_two[$product['product_id']]['product_description'];
    $new_array[$product['product_id']] = $product;
}

您可以使用 array_map 函数的一个选项:

$n_arr = array_map(function ($row) use ($array_two){
    foreach ($array_two as $item){
        if($item['product_id'] == $row['product_id']){
            return $item + $row;
        }
    }
    return false;
},$array_one);