Array opareas
(
[0] => Array
(
[name] = => array('opname1')
[subcats] => Array
(
[0] => Array
(
[amount] => 9883
[perc] => 112.61394712853236
)
[1] => Array
(
[amount] => 1
[perc] => 0.011394712853236098
)
[2] => Array
(
[amount] => 3679
[perc] => 41.921148587055605
)
)
)
[1] => Array
(
[name] = => array('opname2')
[subcats] => Array
(
[0] => Array
(
[amount] => 12166
[perc] => 56.8584380987989
)
[1] => Array
(
[amount] => 1473
[perc] => 6.884142636818245
)
[2] => Array
(
[amount] => 955
[perc] => 4.463242510632331
)
[3] => Array
(
[amount] => 6802
[perc] => 31.789503201383372
)
)
)
PHP非常適合排序數組,但我無法弄清楚在遇到這個問題時要使用什麼。請看一下上面的數組。僅通過特定的鍵值對「內部」數組排序 - 使用uasort()?
我想排序innner subcats[]
array by perc
-key從低到高。
我想要得到的結果是:
Array opareas
(
[0] => Array
(
[name] = => array('opname1')
[subcats] => Array
(
[0] => Array
(
[amount] => 1
[perc] => 0.011394712853236098 //Lowest percentage value
)
[1] => Array
(
[amount] => 3679
[perc] => 41.921148587055605
)
[2] => Array
(
[amount] => 9883
[perc] => 112.61394712853236 //Highest percentage value
)
)
)
[1] => Array
(
[name] = => array('opname2');
[subcats] => Array
(
[0] => Array
(
[amount] => 955
[perc] => 4.463242510632331 //Lowest percentage value
)
[1] => Array
(
[amount] => 1473
[perc] => 6.884142636818245
)
[2] => Array
(
[amount] => 12166
[perc] => 56.8584380987989
)
[3] => Array
(
[amount] => 6802
[perc] => 31.789503201383372 //Highest percentage value
)
)
)
我試過這個:
class whateverArray {
private function sort_subcats_perc($a, $b) {
if ($a['subcats']['perc'] == $b['subcats']['perc']) {return 0;}
return ($a['subcats']['perc'] < $b['subcats']['perc']) ? -1 : 1;
}
public function showStuff() {
$opareas = array(); //Given above
//Sort subcat array from low to high based on perc-key
uasort($opareas, array($this, 'sort_subcats_perc'));
}
);
}
我不想實際opareas[0]
和operas[1]
切換位置(是使用我試過的函數時發生的事情),我只想要內部數組subcats []來改變它的基於perc-field/key的順序。這可能與uasort
?或者其他PHP內置的優秀分類功能?
謝謝!像魅力一樣工作! – bestprogrammerintheworld