I have the following array:
[
{
amendment: 1,
lcnumber: "A1114564564CT",
31D: "New Note"
},
{
27: "0/0 (Number)(Total)",
amendment: 1,
lcnumber: "A1114564564CT",
},
{
amendment: 2,
lcnumber: "A1114564564CT",
31D: "IN SINGAPORE (120 Days from L/C issue date)",
32B: "USD"
},
{
27: "2/2 (Number)(Total)",
amendment: 2,
lcnumber: "A1114564564CT",
39B: "Exceeding"
}
]
What I'm trying to do, is to combine the values into one index with the same amendment
count
This is my expected output
[
{
amendment: 1,
lcnumber: "A1114564564CT",
31D: "New Note",
27: "0/0 (Number)(Total)",
},
{
amendment: 2,
lcnumber: "A1114564564CT",
31D: "IN SINGAPORE (120 Days from L/C issue date)",
32B: "USD",
27: "2/2 (Number)(Total)",
39B: "Exceeding"
},
]
I've tried writing a foreach
loop but this didn't work
foreach($final_datas as $arrflight) {
$final_array[] = (object) array(
'lcnumber' => 'AZ300',
$arrflight['swift_code'] => $arrflight['note']
);
}
My Answer:
Here is a possible solution using PHP:
php
$input_array = [
[
'amendment' => 1,
'lcnumber' => 'A1114564564CT',
'31D' => 'New Note'
],
[
'27' => '0/0 (Number)(Total)',
'amendment' => 1,
'lcnumber' => 'A1114564564CT',
],
[
'amendment' => 2,
'lcnumber' => 'A1114564564CT',
'31D' => 'IN SINGAPORE (120 Days from L/C issue date)',
'32B' => 'USD'
],
[
'27' => '2/2 (Number)(Total)',
'amendment' => 2,
'lcnumber' => 'A1114564564CT',
'39B' => 'Exceeding'
]
];
$final_array = [];
foreach ($input_array as $item) {
$amendment = $item['amendment'];
if (!isset($final_array[$amendment])) {
$final_array[$amendment] = [
'amendment' => $amendment,
'lcnumber' => $item['lcnumber']
];
}
unset($item['amendment']);
unset($item['lcnumber']);
$final_array[$amendment] = array_merge($final_array[$amendment], $item);
}
$final_result = array_values($final_array);
print_r($final_result);
This code will combine the values with the same 'amendment' key into one index in the final array as you expected.
Rate this post
5 of 5 based on 4452 votesComments