CodeIgniter:在视图中使用foreach的问题

时间:2010-04-29 15:18:17

标签: php codeigniter foreach

我有一个模型和控制器从我的数据库中获取一些数据并返回以下数组

Array
(
    [2010] => Array
        (
            [year] => 2010
            [months] => Array
                (
                    [0] => stdClass Object
                        (
                            [sales] => 2
                            [month] => Apr
                        )

                    [1] => stdClass Object
                        (
                            [sales] => 1
                            [month] => Nov
                        )

                )

        )

    [2011] => Array
        (
            [year] => 2011
            [months] => Array
                (
                    [0] => stdClass Object
                        (
                            [sales] => 1
                            [month] => Nov
                        )

                )

        )

)

它显示了它应该显示的内容,但键的名称不同,所以我不知道如何在我看来使用foreach循环这些年。阵列是我不太擅长的东西:(

如果您需要知道,这是控制器:

    function analytics()
    {
        $this->load->model('admin_model'); 
        $analytics = $this->admin_model->Analytics();
        foreach ($analytics as $a):
            $data[$a->year]['year'] = $a->year;
            $data[$a->year]['months'] = $this->admin_model->AnalyticsMonth($a->year);
        endforeach;

        echo"<pre style='text-align:left;'>";
        print_r($data);
        echo"</pre>";

        $data['main_content'] = 'analytics';
        $this->load->view('template_admin', $data);
    }//end of function categories()

1 个答案:

答案 0 :(得分:2)

将数组中的数组放在数组中的单独索引中,以便将其隔离

foreach ($analytics as $a) {
    $data['dates'][$a->year]['year'] = $a->year;
    $data['dates'][$a->year]['months'] = $this->admin_model->AnalyticsMonth($a->year);
}

然后你可以循环使用它而不必担心其他数据

<?php foreach( $dates as $year => $year_content  ): ?>
<h2><?php echo $year ?></h2>

<?php foreach( $year_content['months'] as $months ): ?>
<h3><?php echo $months->month ?> - <?php echo $months->sales ?></h3>
<?php endforeach; ?>

<?php endforeach; ?>