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

Laravel开发API:如何将重复键数组转为动态键值数组

如何将含动态重复键的数组转换为分组数组

原始数组结构

$originalArray = [
  0 => ["Contact Info" => 75],
  1 => ["Contact Info" => 76],
  2 => ["Contact Info" => 77],
  // ... 其他元素
  22 => ["Address Info" => 85],
  23 => ["Address Info" => 86],
  24 => ["Address Info" => 87],
];

目标数组结构

$temp = [
  "Contact Info" => ["75","76","77",...],
  "Address Info" => ["85","86","87",...]
];

解法1:原生PHP循环实现

直接遍历数组,动态收集每个键对应的值:

$temp = [];
foreach ($originalArray as $item) {
    // 获取子数组的唯一键(每个子数组仅含一个键值对)
    $key = array_key_first($item);
    $value = $item[$key];
    
    // 初始化键对应的数组(若不存在则创建)
    if (!isset($temp[$key])) {
        $temp[$key] = [];
    }
    // 将值转为字符串后追加到对应数组
    $temp[$key][] = (string)$value;
}

解法2:Laravel 集合简化实现

利用Laravel集合的链式方法,代码更简洁:

$temp = collect($originalArray)->reduce(function ($result, $item) {
    $key = array_key_first($item);
    $result[$key][] = (string)$item[$key];
    return $result;
}, []);

也可以用groupBy结合map的写法:

$temp = collect($originalArray)
    ->groupBy(fn($item) => array_key_first($item))
    ->map(fn($group) => $group->pluck(array_key_first($group->first()))->map(fn($val) => (string)$val)->toArray())
    ->toArray();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:10:22