Maison > Questions et réponses > le corps du texte
J'ai une liste contenant des activity_code
的数组。我需要在项目字段中添加 pri
enregistrements
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 ) ) )
items
Il devrait y avoir 2 tableaux dans le champ, mais je n'ai inséré qu'un seul tableau.
Voici le code, ce que j'ai essayé.
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; }
C'est la structure de tableau dont j'ai besoin
Quelqu'un peut-il me dire quelle erreur je fais ici ?
P粉6429198232024-02-18 16:25:14
Vous couvrez $purchaseArray[$purchaseRequisition['activity_code']]
,而不是向其中推送新元素。要推入数组,请分配给 $array[]
.
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; }
P粉7242568602024-02-18 15:58:30
Utilisez le code ci-dessous :
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'] = $items; }