Issue
I have two arrays of data coming from an HTML form.
Array1 (payment_descriptions) looks like this:
["1st Desc","2nd Desc","3rd Desc"]
And Array2 (payment_amounts) like this:
["100.10","10.50","39.99"]
Is there a way to combine these arrays (payments) so that the end result will look like this?
[{
"description": "1st Desc",
"amount": "100.10"
}, {
"description": "2nd Desc",
"amount": "10.50"
}, {
"description": "3rd Desc",
"amount": "39.99"
}]
Solution
You can do it with simple array_combine()
and a foreach()
loop:
<?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
Without array_combine()
:
foreach($arr1 as $k=>$v){
$expected[$k] = ['description'=>$v,'amount'=>$arr2[$k]];
}
DEMO: https://3v4l.org/6FVHe
Answered By - A l w a y s S u n n y
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.