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

Laravel控制器中基于公共ID合并两个数组的实现方法咨询

Laravel 控制器数组合并实现方案

实现逻辑

  • 先处理在线人数数组,生成「频道ID => 在线人数」的映射表,提升后续匹配效率
  • 遍历聊天室列表数组,为每个元素匹配对应在线人数,无匹配时默认赋值0

代码实现

Laravel 集合写法(推荐)

// 以下 $rooms 为你提到的数组1(聊天室列表数组),$channelData 为你提到的数组2(在线人数返回数据)
// 若你拿到的是JSON字符串,先转数组:
// $rooms = json_decode($roomsJson, true);
// $channelData = json_decode($channelJson, true);

// 1. 生成ID与在线人数的映射表
$userCountMap = collect($channelData['channels'])
    ->mapWithKeys(function ($item, $channelKey) {
        $roomId = (int)str_replace('presence-chat.', '', $channelKey);
        return [$roomId => $item['user_count']];
    })->toArray();

// 2. 合并数据得到最终数组
$mergedList = collect($rooms)
    ->map(function ($roomItem) use ($userCountMap) {
        $roomItem['user_count'] = $userCountMap[$roomItem['id']] ?? 0;
        return $roomItem;
    })->toArray();

原生PHP写法

$userCountMap = [];
foreach ($channelData['channels'] as $channelKey => $value) {
    $roomId = (int)str_replace('presence-chat.', '', $channelKey);
    $userCountMap[$roomId] = $value['user_count'];
}

$mergedList = [];
foreach ($rooms as $roomItem) {
    $roomItem['user_count'] = isset($userCountMap[$roomItem['id']]) ? $userCountMap[$roomItem['id']] : 0;
    $mergedList[] = $roomItem;
}

说明

最终得到的$mergedList就是你需要的结构,原有字段全部保留,新增了user_count字段。无在线人数匹配的聊天室会默认赋值0,你可以根据需求调整默认值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 21:45:03