经过太多时间对我期望的直接任务进行故障排除后,我相信我或者错过了一个明显的缺陷,或者构建了一个错误的心智模型,告诉我们应该如何运作。
我的实际数据要复杂得多,但我已将其简化为此示例。
我们说我有一个$my_array
个对象:
$object1 = new stdClass();
$object1->valueA = 'abc';
$object1->valueB = 'def';
$object1->valueC = '20160410';
$object2 = new stdClass();
$object2->valueA = '123';
$object2->valueB = '456';
$object2->valueC = '20160408';
$object3 = new stdClass();
$object3->valueA = 'foo';
$object3->valueB = 'bar';
$object3->valueC = '20160412';
$my_array = array(
'X' => $object1,
'Y' => $object2,
'Z' => $object3
);
我想浏览每个对象,使用其中一个值来计算新属性,然后使用新的计算值将对象分配给新数组。
我是这样做的:
$new_array= array();
foreach($my_array as $key=>$obj){
for($i=0;$i<=2;$i++){ //the real use case uses a slightly different loop, this is simpler/shorter for an example
$date = $obj->valueC + $i; //use valueC and the loop to calculate a new value
$obj->date = $date; //add my new value to the object
$new_array[$date][$key] = $obj; //construct new array of arrays of objects. bits on bits on bytes.
}
}
如果我将结果数组记录到Console,它看起来像这样:
[04-Apr-2016 22:09:28 UTC] Array
(
[20160410] => Array
(
[X] => stdClass Object
(
[valueA] => abc
[valueB] => def
[valueC] => 20160410
[date] => 20160412
)
[Y] => stdClass Object
(
[valueA] => 123
[valueB] => 456
[valueC] => 20160408
[date] => 20160410
)
)
[20160411] => Array
(
[X] => stdClass Object
(
[valueA] => abc
[valueB] => def
[valueC] => 20160410
[date] => 20160412
)
)
[20160412] => Array
(
[X] => stdClass Object
(
[valueA] => abc
[valueB] => def
[valueC] => 20160410
[date] => 20160412
)
[Z] => stdClass Object
(
[valueA] => foo
[valueB] => bar
[valueC] => 20160412
[date] => 20160414
)
)
[20160408] => Array
(
[Y] => stdClass Object
(
[valueA] => 123
[valueB] => 456
[valueC] => 20160408
[date] => 20160410
)
)
[20160409] => Array
(
[Y] => stdClass Object
(
[valueA] => 123
[valueB] => 456
[valueC] => 20160408
[date] => 20160410
)
)
[20160413] => Array
(
[Z] => stdClass Object
(
[valueA] => foo
[valueB] => bar
[valueC] => 20160412
[date] => 20160414
)
)
[20160414] => Array
(
[Z] => stdClass Object
(
[valueA] => foo
[valueB] => bar
[valueC] => 20160412
[date] => 20160414
)
)
)
现在,我希望$ new_array [&#39; 20160410&#39;] [&#39; X&#39;] - &gt;日期为20160410
。毕竟,在2行内,我说,&#34;使用此值作为顶级数组键,并将其作为对象中的值&#34;。但无论我做什么,['X']
的所有实例都具有相同的date
值。 ['Y']
和['Z']
相同。
我的目标是能够将新计算的date
值存储在对象中,同时还将该值用作分组键。