2012-06-25 49 views
1

這裏是一種情況:多維數組排序

蒂姆,羅布和吉姆住在一起。吉姆有一把吉他,他賣給了蒂姆。吉姆用這筆錢買了一雙新的時髦鞋。 Rob意外地摔壞了Tim的吉他(他從Tim那裏買來的),此後,Rob向Tim發出一聲玩具吉他的鼓勵,Tim用它來休息。

這裏是在房間裏完成的一系列活動,最新活動第一。

$all_users_activities = array( 
    case1 => array(username =>'Tim', activity => 'broken', object_type => 'toy', objectname=> 'Guitar'), 
    case2 => array(username =>'Rob', activity => 'gifted', object_type => 'toy', objectname=> 'Guitar'), 
    case3 => array(username =>'Rob', activity => 'broken', object_type => 'music', objectname=> 'Guitar'), 
    case4 => array(username =>'Tim', activity => 'bought', object_type => 'music', objectname=> 'Guitar'), 
    case5 => array(username =>'Jim', activity => 'bought', object_type => 'fashion', objectname=> 'shoes'), 
    case6 => array(username =>'Jim', activity => 'sold', object_type => 'music', objectname=> 'Guitar') 
    ); 

現在,我要根據排序這樣的數據:

  1. 用戶名
  2. 對象名(其中 'OBJECT_TYPE' 是一樣的: 'toy''guitar' 是'音樂」不同吉他')
  3. 活動
+0

你應該看看http://php.net/manual/fr/function.usort.php –

+0

另外,如果你使用搜索,你會發現這些:http://stackoverflow.com/questions/tagged /多維數組+ PHP +數組排序 – poncha

+0

[在PHP中排序多維數組?](http://stackoverflow.com/questions/1795244/sorting-a-multidimensional-array-in-php) –

回答

0

檢查了這一點

function aasort (&$array, $key) { 
    $sorter=array(); 
    $ret=array(); 
    reset($array); 
    foreach ($array as $ii => $va) { 
     $sorter[$ii]=$va[$key]; 
    } 
    asort($sorter); 
    foreach ($sorter as $ii => $va) { 
     $ret[$ii]=$array[$ii]; 
    } 
    $array=$ret; 
    echo "<pre>"; 
    print_r($array); 
} 
$all_users_activities=array( 
    case1 => array('username' =>'Tim', activity => 'broken', object_type => 'toy', objectname=> 'Guitar'), 
    case2 => array('username' =>'Rob', activity => 'gifted', object_type => 'toy', objectname=> 'Guitar'), 
    case3 => array('username' =>'Rob', activity => 'broken', object_type => 'music', objectname=> 'Guitar'), 
    case4 => array('username' =>'Tim', activity => 'bought', object_type => 'music', objectname=> 'Guitar'), 
    case5 => array('username' =>'Jim', activity => 'bought', object_type => 'fashion', objectname=> 'shoes'), 
    case6 => array('username' =>'Jim', activity => 'sold', object_type => 'music', objectname=> 'Guitar') 
    ); 
aasort($all_users_activities,"username"); 
+0

我認爲我的答案適合你...請接受答案,如果你認爲它通過點擊勾號標記幫助.... – Wazzzy

+0

是Wasim,它確實爲我工作,我會得到回到這裏,如果我感到困惑的一半:) –

+0

@doing_something_wonderful感謝您接受...我欣賞那... – Wazzzy