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

时间:2015-06-20 17:51:19

标签: php tree

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

ToRightOf

我需要以下列方式打印

2014
JAN
    罗恩
    山姆
AUG
塞缪尔
2015年
1月丹尼尔

1 个答案:

答案 0 :(得分:0)

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

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";
        }
    }
}