I have a array of date and name; I need to show it in tree structure in a minimum code.
$myarray = Array
(
[0] =>
Array
(
'Name' => 'Ron',
'date' => '2014-01-05'
)
[1] =>
Array
(
'Name' => 'Sam',
'Value' => '2014-01-10'
)
[2] =>
Array
(
'Name' => 'Samuel',
'date' => '2014-08-25'
)
[3] =>
Array
(
'Name' => 'Deniel',
'Value' => '2015-01-10'
)
);
I need to print in following ways
2014
JAN
Ron
Sam
AUG
Samuel
2015
JAN
Daniel
If the your input array is already sorted(prepared) by date and name for printing:
foreach ($myarray as $item) {
$date = explode('-', $item['date']);
if (empty($year) || $year != $date[0]) {
$year = $date[0];
print "{$year}
";
}
if (empty($month) || $month != $date[1]) {
$month = $date[1];
print "\t" . strtoupper(date("M", mktime(0, 0, 0, $month, 1, $year))) . "
";
}
print "\t\t{$item['Name']}
";
}
If the input array is need to be sorted(prepared) before being printing:
// Dissecting input array by years and months
$resultArray = array();
foreach ($myarray as $item) {
$date = explode('-', $item['date']);
if (!array_key_exists($date[0], $resultArray)) {
$resultArray[$date[0]] = array();
}
if (!array_key_exists($date[1], $resultArray[$date[0]])) {
$resultArray[$date[0]][$date[1]] = array();
}
$resultArray[$date[0]][$date[1]][] = $item['Name'];
}
// Printing the result
ksort($resultArray);
foreach ($resultArray as $year => $yearItems) {
print "{$year}
";
ksort($yearItems);
foreach ($yearItems as $month => $monthNames) {
print "\t" . strtoupper(date("M", mktime(0, 0, 0, $month, 1, $year))) . "
";
sort($monthNames); // You may remove this line if you don`t need sorting by names
foreach ($monthNames as $name) {
print "\t\t{$name}
";
}
}
}