2016-08-30 77 views
-1

在一個PHP中我有一個這樣的數組。在二維數組中按鍵排序數組

$task_array = array(
    '0' => array('task_name' => 'tsk3','task_chapter_name' => 'chapter3'), 
    '1' => array('task_name' => 'tsk1','task_chapter_name' => 'chapter1'), 
    '2' => array('task_name' => 'tsk2','task_chapter_name' => 'chapter2'), 
    '3' => array('task_name' => 'tsk6','task_chapter_name' => 'chapter6'), 
    '4' => array('task_name' => 'tsk4','task_chapter_name' => 'chapter3'), 
    '5' => array('task_name' => 'tsk6','task_chapter_name' => 'chapter4'), 
    '6' => array('task_name' => 'tsk6','task_chapter_name' => 'chapter7') 
); 

我想要做的是task_chapter_name但一個條件排序是有,如果task_chapter_name值相同,則下一個排序應該task_name明智的。

所需的輸出

$task_array = array(
    '0' => array('task_name' => 'tsk1','task_chapter_name' => 'chapter1'), 
    '1' => array('task_name' => 'tsk2','task_chapter_name' => 'chapter2'), 
    '2' => array('task_name' => 'tsk3','task_chapter_name' => 'chapter3'), 
    '3' => array('task_name' => 'tsk4','task_chapter_name' => 'chapter3'), 
    '4' => array('task_name' => 'tsk6','task_chapter_name' => 'chapter4'), 
    '5' => array('task_name' => 'tsk6','task_chapter_name' => 'chapter6'), 
    '6' => array('task_name' => 'tsk6','task_chapter_name' => 'chapter7') 
); 

我的問題被標記爲複製,但在這裏,我想告訴你,我有優先與多維數組排序,我的首要任務是通過task_chapter_name現在如果我要進行排序在task_chapter_name獲得相同的值,那麼它應該排序task_name

+0

難道在這之前...死守。 – Aaron

+0

好的。 。 waittting ,. , –

+3

http://stackoverflow.com/a/3233009/3355243 – Linesofcode

回答

2
foreach ($task_array as $key => $row) { 
    $taskChapterName[$key] = $row['task_chapter_name']; 
    $taskName[$key] = $row['task_name']; 
} 
array_multisort($taskChapterName, SORT_ASC, $taskName, SORT_ASC, $task_array); 
+0

其返回1個:-( –

+0

運行此代碼後@PunitGajjar檢查'$ task_array'的解決方案。 – Aaron

+0

。偉人,謝謝。其工作 –

0

提取的列和進行排序他們,最後排序最初的陣列。顯然,你可以使用不同的陣列SORT_ASCSORT_DESC不同的訂單:

array_multisort(array_column($task_array, 'task_chapter_name'), 
       array_column($task_array, 'task_name'), 
       $task_array); 

PHP> = 5.5.0是需要array_column()或使用PHP Implementation of array_column()。或者你可以遍歷並建立陣列在上面的排序使用:

foreach($task_array as $val) { 
    $chap[] = $val['task_chapter_name']; 
    $task[] = $val['task_name']; 
}