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

PHP合并含重复键的数组(保留重复键)求助

解决PHP合并重复键数组的问题

嘿,我懂你碰到的麻烦了——用array_combine()处理重复键的时候,后面的值会直接覆盖前面的,而且你之前用的带create_function()的自定义函数因为PHP版本更新(PHP 7.2+已经废弃这个函数了)没法正常工作对吧?别担心,这里有几个靠谱的解决方案,完全适配现代PHP版本:

首先得明确一个关键点:PHP的数组键是唯一的,所以你期望的那种同一个键重复出现三次的数组在PHP里是不可能实现的——后面的键值对会直接覆盖前面的。正确的做法是把同一个邮箱对应的所有标题存成一个数组,这样就能保留所有关联数据啦。

方法一:用普通foreach循环(最直观)

这种方法逻辑简单,容易理解和调试,适合大多数场景:

// 你的原始数组
$title = ['Distributor', 'Internal', 'Agency'];
$email = ['test@test.com', 'test@test.com', 'test@test.com'];

$result = [];

foreach ($email as $index => $mail) {
    // 如果当前邮箱已经作为键存在
    if (isset($result[$mail])) {
        // 先判断当前值是不是数组,避免第一次是字符串的情况
        if (!is_array($result[$mail])) {
            $result[$mail] = [$result[$mail]];
        }
        // 追加新的标题到数组里
        $result[$mail][] = $title[$index];
    } else {
        // 邮箱不存在的话,直接赋值标题(单个值时是字符串,保持简洁)
        $result[$mail] = $title[$index];
    }
}

// 输出结果
print_r($result);

运行后得到的结果是:

Array
(
    [test@test.com] => Array
        (
            [0] => Distributor
            [1] => Internal
            [2] => Agency
        )

)

如果你的场景里大部分邮箱都是唯一的,只有少数重复,这个方法会自动处理:唯一邮箱对应单个字符串值,重复邮箱对应数组值,非常灵活。

方法二:用array_map + array_reduce(函数式写法)

如果你更喜欢函数式编程的风格,可以用这两个函数组合实现,逻辑同样清晰:

// 你的原始数组
$title = ['Distributor', 'Internal', 'Agency'];
$email = ['test@test.com', 'test@test.com', 'test@test.com'];

// 先把两个数组合成包含邮箱和标题的关联数组集合
$combinedItems = array_map(function ($e, $t) {
    return ['email' => $e, 'title' => $t];
}, $email, $title);

// 用array_reduce合并成目标结构
$result = array_reduce($combinedItems, function ($accumulator, $item) {
    $mail = $item['email'];
    
    // 如果邮箱还没在结果数组里,先初始化一个空数组
    if (!isset($accumulator[$mail])) {
        $accumulator[$mail] = [];
    }
    
    // 追加标题到对应邮箱的数组中
    $accumulator[$mail][] = $item['title'];
    
    // 可选:如果只有一个标题,把数组转成单个字符串(保持结果简洁)
    if (count($accumulator[$mail]) === 1) {
        $accumulator[$mail] = $accumulator[$mail][0];
    }
    
    return $accumulator;
}, []);

// 输出结果
print_r($result);

这个方法的好处是把“组合元素”和“合并数组”的逻辑分开,代码可读性更高,适合处理更复杂的数组合并场景。

内容的提问来源于stack exchange,提问作者user2450639

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:19:09