phparraysmultidimensional-arraymappingmerging-data

Map values from a 2d array to another 2d array related by a shared column otherwise use a default of zero


I need to merge the data between two 2d array related by a shared column value. If there is no shared value found, the result array should apply a default value of zero for the new column.

$mahasiswa = [
    ['npm' => 1123123123, 'nama' => 'LINDA'],
    ['npm' => 121323131, 'nama' => 'SETIADI'],
    ['npm' => 12312312, 'nama' => 'WIWIN'],
    ['npm' => 12345678910, 'nama' => 'ABDUL IMAN'],
    ['npm' => 12355141, 'nama' => 'KOKOM'],
    ['npm' => '123U4148U90', 'nama' => 'JIHAN'],
    ['npm' => 978687999, 'nama' => 'KURNIA']
];

$piutang = [
    ['total' => 14600000, 'nama' => 'KOKOM', 'npm' => 12355141],
    ['total' => 8000000, 'nama' => 'KURNIA', 'npm' => 978687999]
];

My current code:

$i = 0;
$rekappiutang = array();
foreach ($mahasiswa as $row) {
   foreach ($piutang as $key=>$val) {
      if ($val['npm'] == $row['npm']) {
         $rekappiutang[$i]['npm']  = $row['npm'];
         $rekappiutang[$i]['nama'] = $row['nama'];
         $rekappiutang[$i]['totalpiutang']  = $val['total'];
       } else {
         $rekappiutang[$i]['npm']  = $row['npm'];
         $rekappiutang[$i]['nama'] = $row['nama'];
         $rekappiutang[$i]['totalpiutang'] = 0;
       }                  
   }
   $i++;
}

Unfortunately, no all related totals re correctly applied to the new column.

My desired result:

[
    ['npm' => 1123123123, 'nama' => 'LINDA', 'total' => 0],
    ['npm' => 121323131, 'nama' => 'SETIADI', 'total' => 0],
    ['npm' => 12312312, 'nama' => 'WIWIN', 'total' => 0],
    ['npm' => 12345678910, 'nama' => 'ABDUL IMAN', 'total' => 0],
    ['npm' => 12355141, 'nama' => 'KOKOM', 'total' => 0],
    ['npm' => '123U4148U90', 'nama' => 'JIHAN', 'total' => 0],
    ['npm' => 978687999, 'nama' => 'KURNIA', 'total' => 0]
]

Solution

  • The problem is your index, each time you get inside the second foreach you overwrite the index position, for example if you get in the first iteration your index will be 0, in the second iteration your index will still be 0 and in this case you'll loose the information you collected in the first iteration, you can do two things depending on how you want to condition your array, you could break outside the first foreach if you find something (if that's what you want to obtain) like this:

    if ($val['npm'] == $row['npm']) {
         $rekappiutang[$i]['npm']  = $row['npm'];
         $rekappiutang[$i]['nama'] = $row['nama'];
         $rekappiutang[$i]['totalpiutang']  = $val['total'];
        break;
    }
    

    Or you could increment the index at the end of the first foreach thus having all the result stored and no overwriting.

    KURNIA works only because it's the last element of the array and after that the foreach breaks automatically.