我有一个动态数组对象,它存储一个像这样的值。
foreach($salesReturn as $salesReturns)
{
echo '<pre>';
print_r($salesReturns);
}
O / P: -
stdClass对象
(
[date] =&gt; 2
[tax1] =&gt; 0.00
[tax2] =&gt; 0.00
[totalReturn] =&gt; 228.95
)
stdClass对象
(
[date] =&gt; 3
[tax1] =&gt; 0.00
[tax2] =&gt; 0.00
[totalReturn] =&gt; 842.55
)
stdClass对象
(
[date] =&gt; 4
[tax1] =&gt; 0.00
[tax2] =&gt; 0.00
[totalReturn] =&gt; 129.33&LT;
)
但是我想在数组对象中存储一个值。
stdClass对象
(
[date] =&gt; 1
[tax1] =&gt; 0.00
[tax2] =&gt; 0.00
[totalReturn] =&gt; 0.00
) stdClass对象
(
[date] =&gt; 2
[tax1] =&gt; 0.00
[tax2] =&gt; 0.00
[totalReturn] =&gt; 228.95
)
stdClass对象
(
[date] =&gt; 3
[tax1] =&gt; 0.00
[tax2] =&gt; 0.00
[totalReturn] =&gt; 842.55
)
stdClass对象
(
[date] =&gt; 4
[tax1] =&gt; 0.00
[tax2] =&gt; 0.00
[totalReturn] =&gt; 129.33
)
stdClass对象
(
[date] =&gt; 5
[tax1] =&gt; 0.00
[tax2] =&gt; 0.00
[totalReturn] =&gt; 0.00
)
stdClass对象
(
[date] =&gt; 6
[tax1] =&gt; 0.00
[tax2] =&gt; 0.00
[totalReturn] =&gt; 0.00
)
stdClass对象
(
[date] =&gt; 7
[tax1] =&gt; 0.00
[tax2] =&gt; 0.00
[totalReturn] =&gt; 0.00
)
stdClass对象
(
[date] =&gt; 8
[tax1] =&gt; 0.00
[tax2] =&gt; 0.00
[totalReturn] =&gt; 0.00
)
stdClass对象
(
[date] =&gt; 9
[tax1] =&gt; 0.00
[tax2] =&gt; 0.00
[totalReturn] =&gt; 0.00
)
stdClass对象
(
[date] =&gt; 10个
[tax1] =&gt; 0.00
[tax2] =&gt; 0.00
[totalReturn] =&gt; 0.00
)
stdClass对象
(
[date] =&gt; 11个
[tax1] =&gt; 0.00
[tax2] =&gt; 0.00
[totalReturn] =&gt; 0.00
)
stdClass对象
(
[date] =&gt; 12个
[tax1] =&gt; 0.00
[tax2] =&gt; 0.00
[totalReturn] =&gt; 0.00
)
答案 0 :(得分:1)
你想要的是用#34;空的&#34;填充数组。默认对象?
$defaults = [];
foreach (range(1, 12) as $m) {
// using non numerical index to avoid reindexing behaviours...
$defaults['m' . $m] = new stdClass;
...
// init default obj
$defaults['m' . $m]->date = $m;
$defaults['m' . $m]->otherFields = 0;
//add all fields
}
接下来使用相同的索引格式按月索引当前数据数组。
$indexedSalesReturn = [];
foreach ($salesReturn as $obj) {
$indexedSalesReturn['m' . $obj->date] = $obj;
}
然后将默认值附加到当前数据。
$indexedSalesReturn += $defaults;
这不会替换现有索引,但会添加不存在的索引。
可选:ksort数组和array_values
编辑: 你应该瞄准这个工作数组(伪代码)
[
'm1' => stdClass { date => 1, ...},
'm2' => stdClass { date => 2, ...},
...
]
答案 1 :(得分:0)
在所有对象上将[date
]属性移动1:
foreach($salesReturn as $salesReturns)
{
echo '<pre>';
$salesReturns->data = $salesReturns->data - 1;
print_r($salesReturns);
}