在智能循环中以树格式打印

Print in tree format in smart loop

我有一组日期和姓名;我需要用最少的代码在树结构中显示它。

$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'
        ) 
 );

我需要通过以下方式打印

2014
一月
罗恩
山姆
八月
塞缪尔
2015
一月
丹尼尔

如果您的输入数组已经按日期和名称排序(准备)以便打印:

foreach ($myarray as $item) {
    $date = explode('-', $item['date']);
    if (empty($year) || $year != $date[0]) {
        $year = $date[0];
        print "{$year}\n\r";
    }
    if (empty($month) || $month != $date[1]) {
        $month = $date[1];
        print "\t" . strtoupper(date("M", mktime(0, 0, 0, $month, 1, $year))) . "\n\r";
    }

    print "\t\t{$item['Name']}\n\r";
}

如果输入数组在打印前需要排序(准备):

// 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}\n\r";
    ksort($yearItems);
    foreach ($yearItems as $month => $monthNames) {
        print "\t" . strtoupper(date("M", mktime(0, 0, 0, $month, 1, $year))) . "\n\r";
        sort($monthNames); // You may remove this line if you don`t need sorting by names
        foreach ($monthNames as $name) {
            print "\t\t{$name}\n\r";
        }
    }
}