OctoberCMS,如何根据上一页的选项对记录数据集(json 结构)的顺序进行排序?

OctoberCMS, how to sort order of the records data set (json structure) by option from previous page?

有谁知道如何根据上一页的值对这条记录数据集进行排序吗?

例如

第一页(上一页):下拉菜单 select 选项值:1,2,3

selected 1 : 将默认记录排序,

selected 2 : 将按兴趣编号排序,

selected 3 : 将按名称排序

第2页(本页)

{offer in offers %}

重新订购为 selected 选项

2nd page's records data set (json structure)

首先很难排序 JSON 相反,我们可以做的是将其转换为 array 然后我们可以对其进行排序,

and i also suggest to move this JSON code in code section of page.

所以现在在您的页面中 code section

// this method will execute at start of page
function onStart() {   

    // you can replace your json data here inside single quotation
    $offers = '[
        { "name" : "a"},
        { "name" : "c"},
        { "name" : "b"}
    ]';    

    // this is orders based on incoming param
    $sortingOrders = [
        // default (no sorting at all)
        1 => 'default', 
        // sort ascending on names
        2 => ['field' => 'name' , 'direction' => 'asc'], 
        // sort ascending on numbers
        3 => ['field' => 'number' , 'direction' => 'asc'],        
        // extra sort descending on names
        4 => ['field' => 'name' , 'direction' => 'desc'], 
    ];    

    // conver json data in-to array
    $arrayOffers = json_decode ($offers, true);    

    // taking paramert of sorting (you can use your own logic here)
    // $order will be 1 2 3 or 4 passed from previous page
    $order = $this->param('order');

    // we do some checks if given order exists
    if( $order && isset($sortingOrders[$order]) && is_array($sortingOrders[$order]) ) {

        // if order is exists we do sorting
        $this->sortBy($sortingOrders[$order]['field'], $arrayOffers, $sortingOrders[$order]['direction']);
    }

    // assign data to page
    $this['arrayOffers'] = $arrayOffers;
}

// helper function will sort the data
function sortBy($field, &$array, $direction = 'asc')
{
    // array is pass by refenence so it will modify it directly

    // sorting logic
    usort($array, function($a, $b) use ($field, $direction) {

        if(!isset($a[$field])) {
            return 0;
        }

        $a = $a[$field];
        $b = $b[$field];
        if ($a == $b) return 0;
        $direction = strtolower(trim($direction));
        if($direction == 'asc') {
            return $a < $b ? -1 : 1;
        }     
        return $a > $b ? -1 : 1;     
    });

    return true;
}

现在在您的页面中 Markup section 只需放置此代码即可显示数据 sorted,因为 arrayOffers 已经排序。

<ul>
    {% for offer in arrayOffers %}
        <li> {{offer.name}}</li>            
    {% endfor %}
</ul>

Now you can use /testing/:order? as page slug

然后您可以将此页面用作

/testingshow default order

/testing/1show default order

/testing/2 将显示 sort asc on names