You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中按规则合并两个关联数组的实现需求

PHP关联数组按指定规则合并的实现

问题背景

现有两个关联数组:

$array1['product'] = ['staff' => 'abc','services' => 0, 'products' => 100, 'total_sales' => 0];
$array2['product'] = ['staff' => 'abc','services' => 150, 'products' => 0, 'total_sales' => 0];

需要合并得到以下结果:

$array['total'] = ['staff' => 'abc','services' => 150, 'products' => 100, 'total_sales' => 0];

合并规则:

  • staff字段值保持一致(两个数组该值相同)
  • services和products字段取对应数组中的非0值
  • total_sales字段固定为0

实现方案

方案一:遍历键名处理

通过遍历数组的每个键,根据字段类型分别处理:

// 定义输入数组
$array1['product'] = ['staff' => 'abc','services' => 0, 'products' => 100, 'total_sales' => 0];
$array2['product'] = ['staff' => 'abc','services' => 150, 'products' => 0, 'total_sales' => 0];

// 初始化结果数组
$result['total'] = [];

foreach ($array1['product'] as $key => $_) {
    match ($key) {
        'staff' => $result['total'][$key] = $array1['product'][$key],
        'services', 'products' => $result['total'][$key] = $array1['product'][$key] ?: $array2['product'][$key],
        'total_sales' => $result['total'][$key] = 0,
    };
}

// 输出结果
print_r($result['total']);

方案二:利用array_merge快速合并后修正

先使用array_merge合并数组(后面的数组会覆盖前面的同键值),再修正需要保留非0值的字段:

$array1['product'] = ['staff' => 'abc','services' => 0, 'products' => 100, 'total_sales' => 0];
$array2['product'] = ['staff' => 'abc','services' => 150, 'products' => 0, 'total_sales' => 0];

// 合并数组,array_merge会用$array2的值覆盖$array1的同键值
$result['total'] = array_merge($array1['product'], $array2['product']);

// 修正products字段:换回$array1中的非0值
$result['total']['products'] = $array1['product']['products'] ?: $result['total']['products'];

// 输出结果
print_r($result['total']);

结果验证

两种方案运行后都会输出符合预期的结果:

Array
(
    [staff] => abc
    [services] => 150
    [products] => 100
    [total_sales] => 0
)

内容的提问来源于stack exchange,提问作者Eldhose P Jose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 18:55:26