html 合并组合两个单个数组并形成一个关联数组

9fkzdhlc  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(138)

我有两个来自HTML表单的数据数组。
Array1(payment_descriptions)看起来像这样:

["1st Desc","2nd Desc","3rd Desc"]

字符串
Array2(payment_amounts)是这样的:

["100.10","10.50","39.99"]


有没有一种方法可以将这些数组(付款)合并组合起来,使最终结果看起来像这样?

[{
    "description": "1st Desc",
    "amount": "100.10"
}, {
    "description": "2nd Desc",
    "amount": "10.50"
}, {
    "description": "3rd Desc",
    "amount": "39.99"
}]

ovfsdjhp

ovfsdjhp1#

你可以用简单的array_combine()foreach()循环来实现:

<?php
$arr1 = ["1st Desc","2nd Desc","3rd Desc"];
$arr2 =["100.10","10.50","39.99"];

$combined = array_combine($arr1,$arr2);
$expected = [];
foreach($combined as $k=>$v){
    $expected[] = ['description'=>$k,'amount'=>$v];
}
echo json_encode($expected,JSON_PRETTY_PRINT);
?>

字符串

DEMO:https://3v4l.org/1tP4c

  • 无 * array_combine()
foreach($arr1 as $k=>$v){
    $expected[$k] = ['description'=>$v,'amount'=>$arr2[$k]];
}

DEMO:https://3v4l.org/6FVHe

相关问题