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]
]
$v['npm'] == $row['npm']a typo in your question? it should be$val['npm'].