All things considered, the real problem is the following, after a second look at your code, how you set the data property. Starting with PHP5, objects are passed / assigned by default link. Remember the days of PHP4? ( $newInstance = &new SomeClass(); ), PHP5 now uses references for objects, so when you do:
$data = array( (object)array('name' => 'myname')
Then all three objects are assigned the same object (by reference!), So if you change it for the first time, all three instances will reflect the same change!
I recently posted a long answer on links in loops here , it might be worth a look, because loop on a link is not the best way to go about your business.
Some code check:
Instead of creating all these arrays and separately relating them to objects, I would simply do this:
$data = array( array('name' => 'myname') ); $posts = array( array('ID' => 1, 'data'=>$data), array('ID' => 2, 'data'=>$data), array('ID' => 3, 'data'=>$data) ); foreach($posts as $k => $post) { $posts[$k]['data'][0]['parentId'] = $posts[$k]['ID']; } $posts = json_decode(json_encode($posts));
At first, json_encode may seem ineffective, only until json_decode it, but json_decode returns objects, not associative arrays by default. I have already run several test scripts several times, as it turned out: the decoding-decoding approach was actually faster than listing each associative array ...