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

PHP如何将三个同索引一维数组合并为按索引分组的二维数组

PHP平行索引数组合并方案

三个数组属于索引严格对齐的平行数据,直接按索引遍历组装即可得到目标结构,不需要复杂处理。

  • 基础遍历写法(兼容性最好,所有PHP版本都支持)
// 你的原始数组
$origin = [
  "extra_charge_item" => [
    0 => "Massage",
    1 => "Pool table",
    2 => "Laundry"
  ],
  "extra_charge_description" => [
    0 => "Paid",
    1 => "Paid",
    2 => "We wash everything"
  ],
  "extra_charge_price" => [
    0 => "200",
    1 => "100",
    2 => "1000"
  ],
];

$newData = [];
foreach ($origin['extra_charge_item'] as $idx => $itemName) {
    $newData[] = [
        $itemName,
        $origin['extra_charge_description'][$idx],
        $origin['extra_charge_price'][$idx]
    ];
}

$final = ['new_data' => $newData];
  • 简写写法(PHP 7.4+支持,用array_map一行实现)
$final = [
    'new_data' => array_map(
        fn($item, $desc, $price) => [$item, $desc, $price],
        $origin['extra_charge_item'],
        $origin['extra_charge_description'],
        $origin['extra_charge_price']
    )
];

注意:以上写法默认三个数组长度一致、索引顺序一一对应,和你给出的业务场景完全匹配。如果存在字段缺项的情况,可以提前用array_pad把三个数组补到相同长度,避免出现索引不存在的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 16:06:23