如何从按ID合并后的数组中提取唯一ID并按日期排序?
解决按日期排序并提取唯一ID的问题
我来帮你搞定这个问题~基于你给出的合并后数组,我们可以用PHP一步步实现需求:
首先,先把你给出的数组转成可操作的PHP变量:
$mergedArray = [ 'abc' => [ ['id' => 7, 'date' => '2018-03-28', 'message' => 'test1'], ['id' => 81, 'date' => '2018-03-27', 'message' => 'test5'], ['id' => 7, 'date' => '2018-03-27', 'message' => 'test9'], ['id' => 5, 'date' => '2018-03-25', 'message' => 'test'] ] ];
步骤1:确保数组按日期排序(可选但保险)
虽然你的原数组已经有排序,但为了确保逻辑严谨,我们用usort()函数按日期降序(最新日期在前)重新排序:
$items = $mergedArray['abc']; usort($items, function($a, $b) { // 按日期降序排列,调换$a和$b可改为升序 return strtotime($b['date']) - strtotime($a['date']); });
步骤2:筛选唯一ID的条目
我们用一个临时数组记录已经出现过的ID,遍历排序后的数组,只保留每个ID的第一条记录(因为已经按日期排序,第一条就是该ID的最新记录):
$uniqueItems = []; $seenIds = []; foreach ($items as $item) { if (!in_array($item['id'], $seenIds)) { $seenIds[] = $item['id']; $uniqueItems[] = $item; } }
步骤3:提取按日期排序的唯一ID列表
如果只需要ID数组,用array_column()提取即可:
$uniqueSortedIds = array_column($uniqueItems, 'id');
最终结果
输出$uniqueSortedIds会得到:
Array ( [0] => 7 [1] => 81 [2] => 5 )
这个列表是按日期从新到旧排序的唯一ID,对应每个ID最新记录的日期顺序。
如果需要保留完整的条目信息,直接使用$uniqueItems即可,它的结构是:
Array ( [0] => Array ( [id] => 7 [date] => '2018-03-28' [message] => 'test1' ), [1] => Array ( [id] => 81 [date] => '2018-03-27' [message] => 'test5' ), [2] => Array ( [id] => 5 [date] => '2018-03-25' [message] => 'test' ) )
小调整:按日期升序排序
如果需要最旧的日期在前,只需要修改排序函数的顺序:
usort($items, function($a, $b) { return strtotime($a['date']) - strtotime($b['date']); });
此时得到的唯一ID顺序会是5, 81, 7。
内容的提问来源于stack exchange,提问作者Brooks
相关产品推荐
相关产品推荐

