Berechnen Sie eine neue Spalte und entfernen Sie andere Spalten innerhalb verschachtelter Objekte eines mehrdimensionale
Posted: 17 Jan 2025, 05:22
Ich erhalte ein Objekt von einer API, das diese Struktur hat:
Ich möchte das Array PriceResponse durchlaufen, um eine neue berechnete Eigenschaft hinzuzufügen und nicht benötigte Eigenschaften von jedem untergeordneten Objekt zu entfernen. Der beste Weg, dies meiner Meinung nach zu tun, bestand darin, ein weiteres Array zu erstellen. Allerdings bekomme ich es scheinbar nicht zum Laufen.
Mein Codierungsversuch:
Dies ist die Ausgabe des geänderten Arrays – es zeigt nur das letzte Ergebnis des priceResultArray:
Code: Select all
{
"success": true,
"quoteId": 11,
"abcValue": 0,
"priceResponse": [
{
"priceId": 1263,
"fPrice": 37.14,
"grossPrice": 44.7,
"priceType": "ABC"
},
{
"priceId": 1263,
"fPrice": 37.14,
"grossPrice": 44.7,
"priceType": "ABC"
},
{
"priceId": 1266,
"fPrice": 550.14,
"grossPrice": 544.7,
"priceType": "DEF"
}
]
}
Mein Codierungsversuch:
Code: Select all
$output_array = json_decode($output);
$modified_array = array();
$priceResultArray = array();
foreach($output_array as $j => $item) {
foreach($output_array->priceResponse as $i => $field) {
$percent = $field->grossPrice * 10 / 100;
$customPrice = $field->grossPrice + $percent;
$priceResultArray['priceId'] = $field->priceId;
$priceResultArray['customPrice'] = $customPrice;
}
$modified_array['success'] = $output_array->success;
$modified_array['quoteId'] = $output_array->quoteId;
$modified_array['priceResponse'] = $priceResultArray;
}
var_dump($modified_array);
Code: Select all
array(3) {
["success"]=>
bool(true)
["quoteId"]=>
int(0011)
["priceResult"]=>
array(5) {
["priceId"]=>
int(1266)
["customPrice"]=>
float(599.17)
}
}