在我看来,Codeigniter和Foreach

时间:2013-01-11 03:34:43

标签: php codeigniter foreach

Soooo,我有这个功能

public function playerslist()
{
    $this->load->database();
    $data = $this->db->get('skaters')->result();
    $this->load->helper('url');
    $this->load->view('playerslist', array('data' => $data));
}

以及我想要做的是在我的视图中使用foreach来返回像这样的数据

<?php 
    foreach($data as $row => $value){
        echo $row;
    }
?>

它只返回0 ...我做了

<?php 
    print_r($data);
?> 

它返回了这个......

Array ( [0] => stdClass Object ( 
    [id] => 1 
    [firstname] => Steve 
    [lastname] => Stamkos 
    [position] => F 
    [team] => TBL 
    [gp2013] => 0 
    [g2013] => 0 
    [a2013] => 0 
    [pm2013] => 0 
    [pim2013] => 0 
    [ppg2013] => 0 
    [ppa2013] => 0 
    [shg2013] => 0 
    [sha2013] => 0 
    [s2013] => 0 
    [s%2013] => 0 
    [fp2013] => 0 
    [gp2012] => 82 
    [g2012] => 60 
    [a2012] => 0 
    [pm2012] => 0 
    [pim2012] => 0 
    [ppg2012] => 0 
    [ppa2012] => 0 
    [shg2012] => 0 
    [sha2012] => 0 
    [s2012] => 0 
    [s%2012] => 0 
    [fp2012] => 0 
    [gp2011] => 0 
    [g2011] => 0 
    [a2011] => 0 
    [pm2011] => 0 
    [pim2011] => 0 
    [ppg2011] => 0 
    [ppa2011] => 0 
    [shg2011] => 0 
    [sha2011] => 0 
    [s2011] => 0 
    [s%2011] => 0 
    [fp2011] => 0 
    [gp2010] => 0 
    [g2010] => 0 
    [a2010] => 0 
    [pm2010] => 0 
    [pim2010] => 0 
    [ppg2010] => 0 
    [ppa2010] => 0 
    [shg2010] => 0 
    [sha2010] => 0 
    [s2010] => 0 
    [s%2010] => 0 
    [fp2010] => 0 
) )

我做错了什么,我是否在foreach中使用$data

1 个答案:

答案 0 :(得分:3)

应该是

foreach($data as $key=>$row)
{
    echo $row->firstname;
}

因为$ data是一个行数组。所以在你的版本中,$ row是数组中行的索引,而$ value是行本身。