dongxuan1314 2015-06-20 17:51
浏览 9
已采纳

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

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

  • 写回答

1条回答 默认 最新

  • dqvzfp6468 2015-06-20 19:03
    关注

    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}
    ";
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算