按可选列对加密数据进行排序(表格排序)

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

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

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



繁华开满天机
浏览 175回答 2
2回答

江户川乱折腾

我无法通过该字段进行排序或它的方向。事实上,你可以。有一个例子:<?php&nbsp; // Example data&nbsp; $data = array(&nbsp; &nbsp; array('name' => 'Gamma',&nbsp; 'val' => 25),&nbsp; &nbsp; array('name' => 'Beta',&nbsp; 'val' => 5),&nbsp; &nbsp; array('name' => 'Alpha', 'val' => 10)&nbsp; );&nbsp; function sortme(&$array, $onfield, $isdesc) {&nbsp; &nbsp; &nbsp;usort($array,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;function($a, $b) use ($onfield, $isdesc) { // 'use' keyword allows to reference external variables from the inside&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // custom method to obtain and comapre data;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $v1 = isset($a[$onfield]) ? $a[$onfield] : NULL;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $v2 = isset($b[$onfield]) ? $b[$onfield] : NULL;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ($v1 < $v2) return ($isdesc ? 1 : -1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; elseif ($v1 > $v2) return ($isdesc ? -1 : 1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else return 0;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Note: the conditions above can be replaced by spaceship operator in PHP 7+:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // return $isdesc ? ($v2 <=> $v1) : ($v1 <=> $v2) ;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; }&nbsp; sortme($data, 'name', false); // sort by `name` ascending&nbsp; print_r($data); // Alpha -> Beta -> Gamma&nbsp; sortme($data, 'val', true); // sort by `val` descending&nbsp; print_r($data); // 25 -> 10 -> 5

回首忆惘然

它提供了一个将额外参数传递给 usrot 函数的示例。function sort_by_term_meta( $terms, $meta )&nbsp;{&nbsp; &nbsp; usort($terms, array(new TermMetaCmpClosure($meta), "call"));}function term_meta_cmp( $a, $b, $meta ){&nbsp; &nbsp; $name_a = get_term_meta($a->term_id, $meta, true);&nbsp; &nbsp; $name_b = get_term_meta($b->term_id, $meta, true);&nbsp; &nbsp; return strcmp($name_a, $name_b);&nbsp;}&nbsp;class TermMetaCmpClosure{&nbsp; &nbsp; private $meta;&nbsp; &nbsp; function __construct( $meta ) {&nbsp; &nbsp; &nbsp; &nbsp; $this->meta = $meta;&nbsp; &nbsp; }&nbsp; &nbsp; function call( $a, $b ) {&nbsp; &nbsp; &nbsp; &nbsp; return term_meta_cmp($a, $b, $this->meta);&nbsp; &nbsp; }}基本上您需要创建一个类函数来进行排序,并且您可以在构造类时传递其他参数(列,方向)。
打开App,查看更多内容
随时随地看视频慕课网APP