I have an array containing common activity_code
. I need to add pri
record
Array ( [0] => Array ( [pr] => Array ( [id] => 1 [activity_code] => 20220101PR0001 [serial_number] => 0001/2022 ) [pri] => Array ( [item] => Item 1 [description] => Description 1 [quantity] => 15 [unit] => Each [unit_price] => 65000.00 ) ) [1] => Array ( [pr] => Array ( [id] => 1 [activity_code] => 20220101PR0001 [serial_number] => 0001/2022 ) [pri] => Array ( [item] => Item 2 [description] => Description 2 [quantity] => 15 [unit] => Each [unit_price] => 2500.00 ) ) )There should be 2 arrays in the
items
field, but I only inserted 1 array.
Here is the code, what I have tried.
foreach ($records as $key => $record) { $purchaseRequisition = $record['pr']; $items = $record['pri']; if (!array_key_exists($purchaseRequisition['activity_code'], $purchaseArray)) { $purchaseArray[$purchaseRequisition['activity_code']] = []; } $purchaseArray[$purchaseRequisition['activity_code']] = [ 'serialNumber' => $record['pr']['serial_number'], 'items' => [] ]; $purchaseArray[$purchaseRequisition['activity_code']]['items'][$key] = $items; }
This is the array structure I need
Can anyone tell me what mistake I'm making here?
You are overriding
$purchaseArray[$purchaseRequisition['activity_code']]
instead of pushing new elements into it. To push into an array, assign to$array[]
.Use the following code: