2011-03-22 58 views
0

可能重複:
Sorting an associative array in PHPPHP代碼來排序數組.....

您好所有,

我有一個像

<?php 
    $data[] = array('id' => 67, 'hits' => 2); 
    $data[] = array('id' => 86, 'hits' => 1); 
    $data[] = array('id' => 85, 'hits' => 6); 
    $data[] = array('id' => 98, 'hits' => 2); 
    $data[] = array('id' => 89, 'hits' => 6); 
    $data[] = array('id' => 65, 'hits' => 7); 
?> 

一個數組,我想sort的基礎上,在這個陣列上hits

請建議一些代碼,幫助我....

在此先感謝

+1

你爲什麼要問一個問題,是複製粘貼從[PHP文檔(http://php.net/manual/ en/function.array-multisort.php)(Example#3)*和*已經有了解決方案? – jensgram 2011-03-22 11:57:05

回答

1

usort()與下面的對比功能:

function cmpHits($a, $b) { 
    return $a['hits'] - $b['hits']; 
} 

(未經測試,uasort()如果你想保持關鍵的聯想。)

-1

試試這個:

array_multi_sort($data, array('edition'=>SORT_DESC)); 

function array_multi_sort($array, $cols) 
{ 
    $colarr = array(); 
    foreach($cols as $col => $order) 
    { 
     $colarr[$col] = array(); 
     foreach ($array as $k => $row) 
     { 
      $colarr[$col]['_'.$k] = strtolower($row[$col]); 
     } 
    } 

    $eval = 'array_multisort('; 
    foreach($cols as $col => $order) 
    { 
     $eval .= '$colarr[\''.$col.'\'],'.$order.','; 
    } 
    $eval = substr($eval,0,-1).');'; 
    eval($eval); 
    $ret = array(); 
    foreach($colarr as $col => $arr) 
    { 
     foreach($arr as $k => $v) 
     { 
      $k = substr($k,1); 
      if (!isset($ret[$k])) $ret[$k] = $array[$k]; 
      $ret[$k][$col] = $array[$k][$col]; 
     } 
    } 
    return $ret; 
} 

資源:http://php.net/manual/en/function.array-multisort.php

+1

使用eval不是(也不應該)是必需的! – fire 2011-03-22 11:56:53