我有以下 PHP 代码来为每个帖子设置 parentId。每个数据的parentId都成为最后一个post ID。我的逻辑有什么问题?
顺便说一句,如果我将其更改为数组,一切都会好起来的。请帮忙!
$data = array(
(object)array('name' => 'myname')
);
$posts = array(
(object)array('ID' => 1, 'data'=>$data),
(object)array('ID' => 2, 'data'=>$data),
(object)array('ID' => 3, 'data'=>$data)
);
foreach($posts as &$post){
$post->data[0]->parentId = $post->ID;
}
print '<pre>';print_r($posts);die;
die;
结果:
Array
(
[0] => stdClass Object
(
[ID] => 1
[data] => Array
(
[0] => stdClass Object
(
[name] => myname
[parentId] => 3 // expect to be 1
)
)
)
[1] => stdClass Object
(
[ID] => 2
[data] => Array
(
[0] => stdClass Object
(
[name] => myname
[parentId] => 3 // expect to be 2 !!!
)
)
)
[2] => stdClass Object
(
[ID] => 3
[data] => Array
(
[0] => stdClass Object
(
[name] => myname
[parentId] => 3
)
)
)
)