Storing objects in an array with php
Solution 1
I would guess that the problem is that you get to the same object every time by reference from the get
function and then add it by reference to the array, resulting in all items in the array being modified when the item gets modified in the get
function. If that is the case, the following should work:
foreach($query->result() as $content)
{
$item = $this->{'mod_'.$content->type}->get($content->id);
print_r($item);
$items[] = clone $item;
}
print_r($items);
Solution 2
When you push $item to $items, it doesn't push the value $item points to but rather the reference itself. You'll need to initialize $item each time:
foreach($query->result() as $content)
{
$item = new stdClass();
$item = $this->{'mod_'.$content->type}->get($content->id);
print_r($item);
$items[] = $item;
}
print_r($items);
Solution 3
You are probably returning references to the item, not the items themselves. It will always the last reference that $item points to.
Paul Dixon
Hey, I'm a Web developer! I use PHP, MySql, CSS and Javascript mostly but have dabbled in loads of other things!
Updated on July 03, 2022Comments
-
Paul Dixon almost 2 years
I have a function that pulls rows from a database, the content->id and content->type are them used to dynamically call amethod in an already loaded model to get and format the objects details. Once the object is returned it is added to array. All is well except that when i come to use the array although it has the correct number of items in it, they all contain the same object even though i know that they are returned different. Im at a complete loss with this one, any help/ideas whould be great!
The code is below:
foreach($query->result() as $content) { $item = $this->{'mod_'.$content->type}->get($content->id); print_r($item); $items[] = $item; } print_r($items);
And the print_r statements produce this:
stdClass Object ( [id] => 30 [type] => page ) stdClass Object ( [id] => 29 [type] => page ) Array ( [0] => stdClass Object ( [id] => 29 [type] => page ) [1] => stdClass Object ( [id] => 29 [type] => page ) )
-
Paul Dixon almost 15 yearsI thought that something like this would be the problem but initializing it each time didnt work. $items[] = clone($item) did however
-
MoshiBin almost 15 yearsOn second examination it's easy to understand why this method won't work; $items is an array filled with $item, which is still a reference. Reinitializing $item means all items will still refer to the same object. As said above, clone() is the way :)