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
相关产品推荐
相关产品推荐

