Storing objects in an array with php

后端 未结 3 1967
攒了一身酷
攒了一身酷 2020-12-31 23:57

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 t

相关标签:
3条回答
  • 2021-01-01 00:27

    You are probably returning references to the item, not the items themselves. It will always the last reference that $item points to.

    0 讨论(0)
  • 2021-01-01 00:31

    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);
    
    0 讨论(0)
  • 2021-01-01 00:32

    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);
    
    0 讨论(0)
提交回复
热议问题