最后在数组中添加的PHP替换了所有存储的数组值

时间:2016-07-05 17:06:45

标签: php arrays codeigniter

我想做的事情:

  1. 从数据库中获取结果。
  2. 通过分配给stdClass获取所需的值。
  3. 将这些对象放在数组中。 (< -The problem)
  4. 输出为JSON。
  5. 对象很好,他们得到正确的值。但是当它们被分配给数组一次时,它们会替换所有先前的数组值。

    我正在使用CodeIgniter来处理数据库内容。

    功能:

    function get_prizes(){
    
        //All prize objects are stored here
        $prizes = array();
    
        //Prize object
        $prize = new stdClass();
        $prize->name1 = '';
        //$prize->type = '';
    
        //Getting the prizes from a simple database table
        $query = $this->db->get('prizes');
    
        if($query->num_rows() > 0){
    
            foreach ($query->result() as $row):
    
                $prize_name = $row->prize_name;
                $prize->name1 = $prize_name;
                //$prize->type = $prize_name;
    
                $prizes[] = $prize;
    
                echo " Item:  " . print_r($prizes, true) . "<br>";
    
            endforeach;
    
        }
    
        echo json_encode($prizes);
    
    }
    

    输出:

    Item: Array ( [0] => stdClass Object ( [name1] => Radio ) ) 
    Item: Array ( [0] => stdClass Object ( [name1] => Television ) [1] => stdClass Object ( [name1] => Television ) ) 
    Item: Array ( [0] => stdClass Object ( [name1] => Toaster ) [1] => stdClass Object ( [name1] => Toaster ) [2] => stdClass Object ( [name1] => Toaster ) ) 
    [{"name1":"Toaster"},{"name1":"Toaster"},{"name1":"Toaster"}]
    

    我尝试过array_push()。也做同样的事情。

1 个答案:

答案 0 :(得分:2)

您需要在foreach循环中实例化对象:

function get_prizes()
{
    // All prize objects are stored here
    $prizes = array();

    // Getting the prizes from a simple database table
    $query = $this->db->get('prizes');
    if ($query->num_rows() > 0) {
        foreach($query->result() as $row):

            // Prize object    
            $prize = new stdClass();

            // $prize->type = '';
            $prize->name1 = $row->prize_name;

            $prizes[] = $prize;

        endforeach;
    }

    echo json_encode($prizes);
}