简体   繁体   中英

Combine array values with specific key has same value

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']
    ); 
}

It is not perfect, but it works. I am sure someone provide a cleaner solution. I have not had enough coffee today.

$finalArray = [];
foreach ($originalArray as $arrParts) {
    if (!array_key_exists($arrParts["amendment"], $finalArray)) {
        $finalArray[$arrParts["amendment"]] = [];
    }
    foreach ($arrParts as $key => $value) {
        $finalArray[$arrParts["amendment"]][$key] = $value;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM