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

PHP如何合并数组中UID相同的元素并保留键最小的项

解决方案

只需一次遍历原数组即可完成需求,核心逻辑为:用临时数组记录已经出现过的UID,仅当首次遇到某UID时,将对应元素存入结果集,即可保证相同UID只保留原数组中下标最小的项。

实现代码如下:

<?php
// 示例输入数组
$input = [
    [
        'id' => '958',
        'uid' => '385',
        'text' => '2021-10-23 08:32:35'
    ],
    [
        'id' => '956',
        'uid' => '385',
        'text' => '2021-10-23 08:31:51'
    ],
    [
        'id' => '957',
        'uid' => '386',
        'timestamp' => '2021-10-23 08:32:12'
    ],
    [
        'id' => '955',
        'uid' => '385',
        'timestamp' => '2021-10-23 08:31:38'
    ]
];

$usedUid = [];
$output = [];

foreach ($input as $item) {
    $currentUid = $item['uid'];
    if (!isset($usedUid[$currentUid])) {
        $output[] = $item;
        $usedUid[$currentUid] = true;
    }
}

// 打印验证结果
print_r($output);
?>

运行上述代码输出的结果和你给出的预期输出完全一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:24:07