按 selectable 列对加密数据进行排序(table 排序)

usort encrypted data by selectable columns (table sorting)

在按列名对 table 进行排序时遇到了一些困难。问题是数据已加密,因此不能仅按所需方向(升序降序)对列进行排序。所以我想我可以使用 usort 但是虽然我可以用它调用一个函数,即 usort( $data, "sortMyData" ); 我不能传递字段来排序或者它的方向。所以要做到这一点,我需要编写一个函数来对根本不理想的每个可能的列进行排序,有没有人知道我可以向 usort 添加另一个参数的方法,该参数将包含其 属性 以进行排序这是方向。

也许另一种方法是将整组数据解密到某个内存中 table 但由于数据已加密且安全,我想知道这是否会为漏洞打开道路!

我最后的选择是将其构建到一个 foreach 循环中,我认为这很有意义,但这是唯一的方法吗?

谢谢

克雷格

参考这个Whosebug问题,Pass extra parameters to usort callback

它提供了一个将额外参数传递给 usrot 函数的示例。

function sort_by_term_meta( $terms, $meta ) 
{
    usort($terms, array(new TermMetaCmpClosure($meta), "call"));
}

function term_meta_cmp( $a, $b, $meta )
{
    $name_a = get_term_meta($a->term_id, $meta, true);
    $name_b = get_term_meta($b->term_id, $meta, true);
    return strcmp($name_a, $name_b); 
} 

class TermMetaCmpClosure
{
    private $meta;

    function __construct( $meta ) {
        $this->meta = $meta;
    }

    function call( $a, $b ) {
        return term_meta_cmp($a, $b, $this->meta);
    }
}

基本上您需要创建一个 class 函数来进行排序,您可以在构造 class.

时传递额外的参数(列、方向)

I can't pass the field to sort or it's direction into it.

事实上,你可以。有个例子:

<?php
  // Example data
  $data = array(
    array('name' => 'Gamma',  'val' => 25),
    array('name' => 'Beta',  'val' => 5),
    array('name' => 'Alpha', 'val' => 10)
  );


  function sortme(&$array, $onfield, $isdesc) {
     usort($array, 
           function($a, $b) use ($onfield, $isdesc) { // 'use' keyword allows to reference external variables from the inside
              // custom method to obtain and comapre data;
              $v1 = isset($a[$onfield]) ? $a[$onfield] : NULL; 
              $v2 = isset($b[$onfield]) ? $b[$onfield] : NULL;

              if ($v1 < $v2) return ($isdesc ? 1 : -1);
              elseif ($v1 > $v2) return ($isdesc ? -1 : 1);
              else return 0; 
              // Note: the conditions above can be replaced by spaceship operator in PHP 7+:
              // return $isdesc ? ($v2 <=> $v1) : ($v1 <=> $v2) ;
           }
          );
  }


  sortme($data, 'name', false); // sort by `name` ascending
  print_r($data); // Alpha -> Beta -> Gamma

  sortme($data, 'val', true); // sort by `val` descending
  print_r($data); // 25 -> 10 -> 5