在PHP中sorting关联数组
我有这种格式的数组:
Array ( [0] => Array ( [text] => tests [language] => [advertiserCompetitionScale] => 5 [avgSearchVolume] => 7480000 [lastMonthSearchVolume] => 9140000 ) [1] => Array ( [text] => personality tests [language] => [advertiserCompetitionScale] => 5 [avgSearchVolume] => 165000 [lastMonthSearchVolume] => 201000 ) [2] => Array ( [text] => online tests [language] => [advertiserCompetitionScale] => 5 [avgSearchVolume] => 246000 [lastMonthSearchVolume] => 301000 ) )
我怎样才能按照avgSearchVolume
字段的降序排列这种格式的数组? 有没有内置的function呢?
使用usort
并提供自己的function来进行sorting,例如
function cmp($a, $b) { return $b['avgSearchVolume'] - $a['avgSearchVolume']; } usort($array, "cmp");
在PHP 5.3之前,这是基于子键sorting的最佳function,不需要为每个键创build新的function。
function sortBySubkey(&$array, $subkey, $sortType = SORT_ASC) { foreach ($array as $subarray) { $keys[] = $subarray[$subkey]; } array_multisort($keys, $sortType, $array); } sortBySubkey($arr, 'avgSearchVolume');
在PHP 5.3中,你可以像现在这样创build类似的函数。
function getSortVariable($sortType = SORT_ASC) { switch($sortType) { case SORT_ASC: return function ($a, $b) use ($subkey) { return strcmp($a[$subkey], $b[$subkey]); }; } } function sortBySubkey(&$array, $subkey, $sortType = SORT_ASC) { $sortFunction = getSortVariable($sortType); usort($array, $sortFunction($subkey)); }
你必须和usort()
一起使用自定义的callback函数。
function cmp($a, $b) { if ($a['avgSearchVolume'] == $b['avgSearchVolume']) { return 0; } return ($a['avgSearchVolume'] > $b['avgSearchVolume']) ? -1 : 1; } usort($array, 'cmp');
这可能有助于: 排列数组的数组
function querySort ($first_Array,$second_Array) { return strcasecmp($first_Array['name'],$second_Array['name']); } echo '<pre>'; usort($main, 'querySort'); print_r($main); die;
这是另一个解决scheme,您可以添加多个选项进行sorting(请参阅代码的评论部分)
<?php $arr=Array( Array("text" => "tests","language" =>"","advertiserCompetitionScale" => 5,"avgSearchVolume" => 7480000,"lastMonthSearchVolume" => 9140000), Array("text" => "personality tests","language" =>"","advertiserCompetitionScale" => 5,"avgSearchVolume" => 165000,"lastMonthSearchVolume"=>201000), Array("text" => "online tests","language" =>"","advertiserCompetitionScale" => 5,"avgSearchVolume" => 246000,"lastMonthSearchVolume" =>301000) ); $sort = array(); foreach($arr as $k=>$v) { $sort['avgSearchVolume'][$k] = $v['avgSearchVolume']; //$sort['text'][$k] = $v['text']; } array_multisort($sort['avgSearchVolume'], SORT_DESC, $arr); //array_multisort($sort['avgSearchVolume'], SORT_DESC, $sort['text'], SORT_ASC,$arr); echo "<pre>"; print_r($arr); ?>
REF: http : //php.net/manual/en/function.array-multisort.php