Reputation: 4828
I have a model and controller who gets some data from my database and returns the following array
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
)
)
)
)
It shows exactly what it should show but the key's have different names so I have no idea on how to loop through the years using foreach in my view. Arrays is something I'm not that good at yet :(
this is the controller if you need to know:
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()
Upvotes: 0
Views: 3847
Reputation: 30170
put the arrays of years in a separate index in the array so you can isolate it
foreach ($analytics as $a) {
$data['dates'][$a->year]['year'] = $a->year;
$data['dates'][$a->year]['months'] = $this->admin_model->AnalyticsMonth($a->year);
}
Then you can loop through that without having to worry about the other data
<?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; ?>
Upvotes: 2