2 回答

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超5個(gè)贊
我無(wú)法通過(guò)該字段進(jìn)行排序或它的方向。
事實(shí)上,你可以。有一個(gè)例子:
<?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

TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超11個(gè)贊
它提供了一個(gè)將額外參數(shù)傳遞給 usrot 函數(shù)的示例。
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);
}
}
基本上您需要?jiǎng)?chuàng)建一個(gè)類(lèi)函數(shù)來(lái)進(jìn)行排序,并且您可以在構(gòu)造類(lèi)時(shí)傳遞其他參數(shù)(列,方向)。
- 2 回答
- 0 關(guān)注
- 196 瀏覽
添加回答
舉報(bào)