Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing objects in an array with php

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
        )

)
like image 884
Paul Dixon Avatar asked Jun 30 '09 17:06

Paul Dixon


People also ask

Can you store objects in an array?

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.

What are the 3 types of PHP arrays?

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.

Can you put variables in an array PHP?

Yes, you can store variables within arrays, though you'll need to remove the space between $result and the opening bracket.

What is difference between array and object in PHP?

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.


1 Answers

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);
like image 163
Mikael Auno Avatar answered Oct 14 '22 23:10

Mikael Auno