Punit Gajjar Punit Gajjar - 3 months ago 8
PHP Question

PHP sort array by key in 2 dimensional array

In a Php i have an Array like this.

$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')
);


What i want to do is sorting by
task_chapter_name
but one more condition is there that if
task_chapter_name
value is same then next sorting should
task_name
wise.

Required Output

$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')
);


My Question is Marked as Duplicate but here i want to inform you that i have priorities sorting with the multidimensional array, My first priority was to sort by
task_chapter_name
now if i am getting same values in
task_chapter_name
then it should be sort with
task_name
.

Answer
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);
Comments