2
我有一個回調函數另一個函數,循環通過我的博客文章的評論。我現在試圖切換到「線程/嵌套」註釋,因此擴展了回調函數。到目前爲止一切正常,但我無法擺脫這種感覺,我沒有根據最佳的PHP實踐(和性能)編寫它。回調函數
我使用一個css框架,並且必須爲我分配給單個註釋的.span-xy
類執行一些數學運算。我從一個全局常量的輸入值開始,例如輸出。 span-12
獲取父級評論。然後,我必須降低/提高每個嵌套級別的+/- (int) 1
的值。所以我來創建數組,對它們進行計數,迭代併爲每個評論構建臨時數組。
問題: 有沒有更容易的方法來解決這個問題?
<!-- This is the final html mark-up output: List of comments (threaded/nested) -->
<ul>
<li id="1" class="push-<?php echo $push; ?> span-<?php echo $span; ?>">comment - parent</li>
<li id="2">comment - child of #1
<ul class="children">
<li id="3">comment - child of #2
<li id="4">comment - child of #2
<ul class="children">
<li id="5">comment - child of #4</li>
</ul>
<li id="6">comment - child of #2</li>
</ul>
<li id="7">comment - child of #2
<ul class="children">
<li id="8">comment - child of #7</li>
<li id="9">comment - child of #7</li>
</ul>
</li>
</li>
</ul>
<?php
// This is my callback function
function comment_list_cb($comment, $args, $depth)
{
// retrieve the data from the globals or make them available
$GLOBALS['comment'] = $comment;
global $post;
static $width = MY_GLOBAL_WIDTH_CONSTANT;
static $ancestors = null;
// is Child/Parent comment
$parent = (int) $comment->comment_parent; // retrieve the ID of the parent
$is_child = false;
if ($parent > (int) 0) // if we got a parent
{
$is_child = true;
if (! (array) $ancestors)
$ancestors = array();
if (! array_key_exists($parent, $ancestors))
{
$ancestors[$parent] = get_comment_ID();
}
else
{
foreach ($ancestors as $parent_id => $child_id)
{
if ($parent_id == $parent)
{
$ancestors_temp[$parent_id] = $child_id;
break;
}
$ancestors_temp[$parent_id] = $child_id;
}
$ancestors = $ancestors_temp;
}
$parent_counter = count($ancestors);
$span = $width - (int) $parent_counter;
}
else
{
$ancestors = $parent_counter = null;
$span = MY_GLOBAL_WIDTH_CONSTANT;
}
$span_txt = $span - (int) 2; // reduce per `2` because of the span-2 class at the avatar element
// now: build the classes
$push = $parent_counter != (int) 0 ? 'push-1' : '';
$child = $is_child === true ? ' child ' : '';
$list = comment_class('span-'.$span.' '.$push.' append-bottom last hreview comment-'.get_comment_ID().' '.$microid, get_comment_ID(), $post->ID, false);
?>
<!-- build the comment -->
<li <?php echo $list; ?>>
<div id="<?php get_comment_ID(); ?>">
<span class="comment-avatar span-2"><!-- display avatar img - width is span-2 --></span>
<span class="comment-meta span-<?php echo $span_txt; ?> last"><!-- display meta data like timestamp, etc. --></span>
<span class="comment-text span-<?php echo $span_txt; ?> last"><!-- display message --></span>
</div>
</li>
<?php
}
英語不是我的母語。什麼是「不需要將int literal轉換爲int。如果你想要int比較,那就是你應該投射的變量。」意思?順便說一句:我解決了前兩件事(從一些嘗試/錯誤的東西遺留下來)。最後一個......是的,你是對的。 – kaiser 2011-05-11 18:10:04
你不需要'(int)2',因爲2已經保證是一個int。 – webbiedave 2011-05-11 18:18:47