[英]Order array by calculated field in javascript or php?
我有一個js函數,正在努力顯示帶有測驗結果的類別列表。 但是,測驗結果是在javascript中計算的,而我創建的php表只是調用沒有結果的初始數組。 這意味着我可以按數組中的任何順序排序,但是我想按測驗%排序。 我應該在js或php中執行此操作嗎?
setCategoryOverview: function() {
results.comp.cats = {};
$e.find('.wpProQuiz_catOverview li').each(function() {
var $this = $(this);
var catId = $this.data('category_id');
if(config.catPoints[catId] === undefined) {
$this.hide();
return true;
}
var r = Math.round(catResults[catId] / config.catPoints[catId] * 100 * 100) / 100;
results.comp.cats[catId] = r;
$this.find('.wpProQuiz_catPercent').text(r + '%');
$this.show();
});
},
這是由category_id排序的php表
<div class="wpProQuiz_catOverview" <?php $this->isDisplayNone($this->quiz->isShowCategoryScore()); ?>>
<h4><?php _e('Categories', 'wp-pro-quiz'); ?></h4>
<div style="margin-top: 10px;">
<ol>
<?php foreach($this->category as $cat) {
if(!$cat->getCategoryId()) {
$cat->setCategoryName(__('Not categorized', 'wp-pro-quiz'));
}
?>
<li data-category_id="<?php echo $cat->getCategoryId();?>">
<span class="wpProQuiz_catName"><?php echo $cat->getCategoryName(); ?></span>
<span class="wpProQuiz_catPercent">0%</span>
</li>
<?php } ?>
</ol>
</div>
</div>
正如JayBlanchard提議的那樣,最好的選擇是生成百分比並事先進行排序(在服務器端)。 但是,這可能不是一個選擇。 您可以嘗試這種方法在客戶端( fiddle )進行整理:
// Pre-calculate the percentages using js as you're doing.
var results = [];
$("ol li").each(function (index, item) {// Store the results in an array of objects.
results.push({
id: $(item).data("category_id"),
name: $(".wpProQuiz_catName", this).text(),
percentage: $(".wpProQuiz_catPercent",this).text()
});
});
results.sort(function(a,b){// Sort the array by percentage.
var numA = +(a.percentage.slice(0,-1)), numB = +(b.percentage.slice(0,-1));
return numB - numA;// Ascending order
});
$("ol li").each(function (index, item) {// Substitute li information acccording to the ordered array.
$(item).attr("data-category_id", results[index].id);
$(".wpProQuiz_catName", this).text(results[index].name);
$(".wpProQuiz_catPercent",this).text(results[index].percentage);
});
由於您是在js中其他位置計算百分比的事實,因此可以用更少的循環來完成(您可以利用該百分比並在那里創建結果數組)。
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.