我想通過一個子數組值來排序我的數組,我使用這個與uasort
,但代碼是醜陋的,看起來它可以做得更好,因爲有很多重複的代碼。通過子數組值改進排序數組
我該如何改進這種開關/箱子的排序?
switch ($this->view->sort_key_num) {
case 1: // Date
if ($this->view->sort_key_type == 1)
krsort($this->view->content);
break;
case 2: // Likes
function sort_like(&$a, &$b) { return ($a['likes'] > $b['likes']) ? 1 : -1; }
uasort($this->view->content, 'sort_like');
if ($this->view->sort_key_type == 1)
$this->view->content = array_reverse($this->view->content);
break;
case 3: // new content
function sort_entries(&$a, &$b) { return ($a['newcontent'] > $b['newcontent']) ? 1 : -1; }
uasort($this->view->content, 'sort_entries');
if ($this->view->sort_key_type == 1)
$this->view->content = array_reverse($this->view->content);
break;
case 4: // comments
function sort_comments(&$a, &$b) { return ($a['comments'] > $b['comments']) ? 1 : -1; }
uasort($this->view->content, 'sort_comments');
if ($this->view->sort_key_type == 1)
$this->view->content = array_reverse($this->view->content);
break;
case 5: // facebook
function sort_facebook(&$a, &$b) { return ($a['facebook'] > $b['facebook']) ? 1 : -1; }
uasort($this->view->content, 'sort_facebook');
if ($this->view->sort_key_type == 1)
$this->view->content = array_reverse($this->view->content);
break;
case 6: // twitter
function sort_twitter(&$a, &$b) { return ($a['twitter'] > $b['twitter']) ? 1 : -1; }
uasort($this->view->content, 'sort_twitter');
if ($this->view->sort_key_type == 1)
$this->view->content = array_reverse($this->view->content);
break;
case 7: // email
function sort_email(&$a, &$b) { return ($a['email'] > $b['email']) ? 1 : -1; }
uasort($this->view->content, 'sort_email');
if ($this->view->sort_key_type == 1)
$this->view->content = array_reverse($this->view->content);
break;
case 8: // google
function sort_google(&$a, &$b) { return ($a['google'] > $b['google']) ? 1 : -1; }
uasort($this->view->content, 'sort_google');
if ($this->view->sort_key_type == 1)
$this->view->content = array_reverse($this->view->content);
break;
case 10: // views
function sort_views(&$a, &$b) { return ($a['views'] > $b['views']) ? 1 : -1; }
uasort($this->view->content, 'sort_views');
if ($this->view->sort_key_type == 1)
$this->view->content = array_reverse($this->view->content);
break;
}
雖然這段代碼是在5.3 php服務器上運行的, 5.2不支持此用戶建議的關閉。不錯的工作,但我仍然堅持在PHP 5.2,所以我沒有考慮關閉方式。看起來像我的,但有5.3的味道... – 2012-01-04 16:12:58
@MathieuDumoulin感謝您的提示,不知道匿名函數沒有實現早。 – kba 2012-01-04 16:24:29