Octobercms - 按页面变量排序前端列表(变量不在数据库中)

Octobercms - Order frontend list by page variable (variable not on database)

所以我正在尝试在 octobercms 上创建一个包含前端用户数据的排行榜, 排行榜将基于当前数据库中的变量总和。最近才开始关注twig和october,请耐心看

通用变量:

{% set totalScore = totalPoints + user.xp + user.progress %}

列表(简体)

{% for user in activatedUsers %}
<div class="card">
        <p class="name"><span class="rank-title">NAME</span><br>{{ user.name }}</p>
        <p><span class="rank-title">LEVEL</span><br>{{ user.level }}</p>
        <p><span class="rank-title">TOTAL POINTS</span><br>{{ totalPoints }} </p>
        <p><span class="rank-title">PROGRESS</span><br>{{ user.progress }}</p>
        <p><span class="rank-title">XP</span><br>{{ user.xp }}</p>
</div>
{% endfor %}

我不能真正使用查询来排序,因为有些变量不在数据库中,而是在页面中定义。 我研究了 sort twig 函数,但我无法让它正常工作。 我试过 this solution,但出现异常。

我添加了以下代码以使 "usort" 函数对 modules/twig/extension 文件起作用,但它不起作用,必须有一个更简单的解决方案...

new \Twig_SimpleFilter('usort', array($this, 'usortFilter'))

public function usortFilter($item){
    usort($item, function ($item1, $item2) {
        if ($item1['orderNo'] == $item2['orderNo']) return 0;
        return $item1['orderNo'] < $item2['orderNo'] ? -1 : 1;
    });

return $item;
}

在阅读了 twig 文档后,我也尝试了合乎逻辑的做法:

{% for user in activatedUsers|sort('totalPoints') %}

但运气不好。 我可能走错了路,所以请随时提出其他建议或指出我错过的事情。 提前致谢

嗯,我不确定你在哪里设置你的 activatedUsers 但在设置之前你可以简单地定义这个循环来对它们进行排序

you should use this only if your dataset is limited in numbers like 10 or 30 entry in list, no more then that its not efficient to sort db records in code

$activatedUsers = <<some code to fetch users>>
$sortedPointsWithUserId = [];
$sortedActivatedUsers = [];

foreach($activatedUsers as $user) {
    // if $totalPoints  is page variable you can use it directly $this->page['totalPoints'] from components and from page lifecycle $this['totalPoints']
    $sortedPointsWithUserId[$user->id] = $totalPoints + $user->xp + $user->progress;
}

// sort array in descending order as we are storing totalpoints as value and key as user ID
// arsort maintain key value association  
arsort($sortedPointsWithUserId);

foreach($sortedPointsWithUserId as $key => $value) {
   $user = $activatedUsers[$key];
   // create variable in model to hold totalPoints so we dont need to calculate again
   $user->totalPoints = $value;
   $sortedActivatedUsers[] = $user;
}

// $sortedActivatedUsers <-- this is your sorted array and you can use it 

如果您有任何疑问,请评论