NewCod3r NewCod3r - 4 months ago 9
SQL Question

PHP MySQL print monthly data using array() not work

I have this code for show monthly data using php and mysql:

$sql = "SELECT title,timestamp,id FROM ".NEWS." ORDER BY timestamp DESC";

$data = DataAccess::Fetch($sql);

$nav = array();

foreach ( $data as $news ) {
$month = date('F', $news['timestamp']);
$nav[$month][$news['id']] = $news['title'];
}


Now In
var_export($nav)
My result is false:

array (
'July' =>
array (
277 => 'title1 for July 2016',
276 => 'title2 for July 2016',
275 => 'title3 for July 2016',
273 => 'title4 for July 2016',
272 => 'title5 for July 2016',
274 => 'title1 for July 2015',
264 => 'title2 for July 2015',
261 => 'title3 for July 2015',
),
'January' =>
array (
243 => 'title for January 2016',
242 => 'title for January 2015',
),
)


In result I see marge data for July 2016 with data with July 2015 Or Merge data for January 2016 With January 2015. I need to Separated Data For July 2016 from July 2015 And January 2016 From January 2015. How do fix problem?

Answer

You are only using the MONTH $month = date('F', $news['timestamp']); as the key to your $nav array. You also need to use the year if you dont want to mix the year data together.

I suggest something like this possibly

$nav = array();

foreach ( $data as $news ) {
    $year = date('Y', $news['timestamp'] );
    $month = date('F', $news['timestamp']);
    $nav[$year][$month][$news['id']] = $news['title'];
}

Or maybe

$nav = array();

foreach ( $data as $news ) {
    $year = date('Y', $news['timestamp'] );
    $month = date('F', $news['timestamp']);
    $nav[$year . '-' . $month][$news['id']] = $news['title'];
}
Comments