将新对象插入对象树.如何



我刚刚创建完这个漂亮的php对象树。如何使用循环将新对象插入items节点数组?基本上如何将新的匿名项对象插入到此对象树中的项数组

看看

<?php 
$phpObjectTree = 
(object)[
'apiVersion' => '1.0',
'data' => (object)[
'requested' => '2020-01-01T23:59:59.001Z',
'status' => 'OK',
'estimate' => (object)[
'id' => '1001',
'type' => 'Commercial',
'client' => (object)[
'name' => 'ABC Construction, Inc.',
'address1' => '123 Main St',
'city' => 'Salt Lake City',
'state' => 'UT',
'postalCode' => '84101'
],
'summary' => (object)[
'generalRequirements' => (object)[
'default' => 0
],
'salesTax' => (object)[
'material' => 4.85,
'labor' => 4.85,
'equipment' => 4.85
],
'overheadProfit' => (object)[
'material' => 10,
'labor' => 10,
'equipment' => 10
],
'contingency' => (object)[
'default' => 3
],
'performanceBond' => (object)[
'default' => 1.3
],
'laborPlus' => (object)[
'dailyRate' => 280,
'crewCount' => 0,
'dayCount' => 0
],
'locationAdjustment' => (object)[
'factor' => 90.1
],
]
],
'items' => [
(object)[
'id' => '2001',
'number' => '09 91 23.00 0000',
'description' => 'Line Item 1',
'quantity' => 0,
'unit' => 'sf',
'material' => (object)[
'cost' => 0,
'costEach' => 9.99
],
'labor' => (object)[
'cost' => 0,
'costEach' => 9.99
],
'equipment' => (object)[
'cost' => 0,
'costEach' => 9.99
],
'lineTotal' => 0
],
(object)[
'id' => '2002',
'number' => '09 91 23.00 0000',
'description' => 'Line Item 2',
'quantity' => 0,
'unit' => 'sf',
'material' => (object)[
'cost' => 0,
'costEach' => 9.99
],
'labor' => (object)[
'cost' => 0,
'costEach' => 9.99
],
'equipment' => (object)[
'cost' => 0,
'costEach' => 9.99
],
'lineTotal' => 0
]
]
]
];
// SET JSON HEADER...
header('Content-type:application/json;charset=utf-8');
print_r(json_encode($phpObjectTree));
?>

与在php:中修改任何数组的方式相同

https://www.php.net/manual/en/language.types.array.php#language.types.array.syntax.modifying

$phpObjectTree->data->items[] = (object)[
'id' => '2003',
'number' => '09 91 23.00 0000',
'description' => 'Line Item 3',
'quantity' => 0,
'unit' => 'sf',
'material' => (object)[
'cost' => 0,
'costEach' => 9.99
],
'labor' => (object)[
'cost' => 0,
'costEach' => 9.99
],
'equipment' => (object)[
'cost' => 0,
'costEach' => 9.99
],
'lineTotal' => 0
];

或者您可以使用stdClass创建新对象并添加属性。

$obj = new stdClass;
$obj->newProperty = 'value';

最新更新