首先,这是我一直在处理的 JSON 响应:
{ "status": "ok",
"permalinks": [
"http:\/\/localhost\/blog\/2012\/06\/",
"http:\/\/localhost\/blog\/2012\/04\/",
"http:\/\/localhost\/blog\/2012\/03\/",
"http:\/\/localhost\/blog\/2011\/10\/"
],
"tree": {
"2012": {
"06": "221",
"04": "2",
"03": "3"
},
"2011": {
"10": "3"
}
}
}
PHP 用于将其格式化为 DIV 中的 HTML UL:
function DisplayResponse(){
$baseref = 'http://localhost/' ;
$url = $baseref . 'api/get_date_index';
$r = file_get_contents( $url ) ;
if( $r !== false ){
$r = json_decode($r,true);
$t = $r['tree'] ;
echo '<div class="sidebar">' ;
echo '<h3>Response</h3>' ;
echo '<ul class="sidebar-list">' ;
for ( $y = 0 ; $y <= 2 ; $y++ ){
if ( $y == 0 ){
for ( $m = 12 ; $m >= 0 ; $m-- ) {
$d = mktime ( 0, 0, 0, $m, 1, Date("Y") ) ;
$du = Date("Y", $d ) ;
$dm = Date("M", $d ) ;
if ( $m < 11 ){
$mm = sprintf("%02d",$m) ;
if ( $t[$du][$mm] != NULL ){
echo '<li><a href="' . $baseref . 'blog/' . $du . '/' . $mm
. '/">' . $dm . ', ' . $du . '</a></li>' ;
}
} else {
if ( $t[$du][$m] != NULL ){
echo '<li><a href="' . $baseref . 'blog/' . $du . '/' . $mm
. '/">' . $dm . ', ' . $du . '</a></li>' ;
}
}
}
} else {
for ( $m = 12 ; $m >= 0 ; $m-- ) {
$d = mktime ( 0, 0, 0, $m, 1, ( Date("Y") - $y) ) ;
$du = Date("Y", $d );
$dm = Date("M", $d ) ;
if ( $m < 11 ){
$mm = sprintf("%02d",$m) ;
if ( $t[$du][$mm] != NULL ){
echo '<li><a href="' . $baseref . 'blog/' . $du . '/' . $mm
. '/">' . $dm . ', ' . $du . '</a></li>' ;
}
} else {
if ( $t[$du][$m] != NULL ){
echo '<li><a href="' . $baseref . 'blog/' . $du . '/' . $mm
. '/">' . $dm . ', ' . $du . '</a></li>' ;
}
}
}
}
}
echo '</ul></div><div class="sidebar-bottom"></div>' ;
}
}
输出是在页面部分以降序显示月份和年份行项目的理想结果,但是我如何清理这段代码以便在源代码中漂亮地显示?