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
)
)
Storing Objects in an arrayYes, since objects are also considered as datatypes (reference) in Java, you can create an array of the type of a particular class and, populate it with instances of that class.
In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.
Yes, you can store variables within arrays, though you'll need to remove the space between $result and the opening bracket.
An object is an instance of a class. It is simply a specimen of a class and has memory allocated. Array is the data structure that stores one or more similar type of values in a single name but associative array is different from a simple PHP array. An array which contains string index is called associative array.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With