如何使用Laravel Collection处理Http Client拉取的赔率数据实现结构转换
Laravel 集合实现赛事赔率数据扁平化方案
前置说明
假设你通过Http Client拉取到数据后,已经转为Laravel集合格式,原始结构示例如下:
$markets = collect([ // 顶层键为市场ID 'market_1' => [ 'code' => 'full_time_result', 'mbc' => 1, 'outcomes' => [ // 赔率项列表 ['id' => 'out1', 'name' => '主胜', 'odds' => 1.85], ['id' => 'out2', 'name' => '平局', 'odds' => 3.4], ['id' => 'out3', 'name' => '客胜', 'odds' => 4.2], ] ], 'market_2' => [ 'code' => 'over_under', 'mbc' => 2, 'outcomes' => [ ['id' => 'out4', 'name' => '大2.5', 'odds' => 1.9], ['id' => 'out5', 'name' => '小2.5', 'odds' => 1.95], ] ] ]);
核心实现代码
用flatMap+map组合即可完成需求:
$flattenedOutcomes = $markets->flatMap(function ($market) { // 遍历当前市场下所有赔率项,追加父级市场的code和mbc字段 return collect($market['outcomes'])->map(function ($outcome) use ($market) { return array_merge($outcome, [ 'market_code' => $market['code'], 'market_mbc' => $market['mbc'], ]); }); }); // 如果需要以outcome的指定字段(比如id)作为顶层键,追加keyBy方法即可 $flattenedOutcomes = $flattenedOutcomes->keyBy('id');
方法说明
flatMap:遍历每个市场项,会自动把每次迭代返回的多组outcome展开拼接为一维集合,避免出现嵌套的二维数组结构。- 内层
map:遍历单个市场下的所有赔率项,通过use引入父级市场数据,将需要的code和mbc字段合并到当前outcome中。 - 如果原始
outcomes字段已经是集合格式,可以省略内层的collect()包裹,直接调用map方法。
输出示例
处理后得到的扁平化结构如下:
[ 'out1' => [ 'id' => 'out1', 'name' => '主胜', 'odds' => 1.85, 'market_code' => 'full_time_result', 'market_mbc' => 1 ], 'out2' => [ 'id' => 'out2', 'name' => '平局', 'odds' => 3.4, 'market_code' => 'full_time_result', 'market_mbc' => 1 ], // 其余赔率项省略 ]
内容的提问来源于stack exchange,提问作者Sercan GÜLER
相关产品推荐
相关产品推荐

