在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
排序,如果我在{{1}中得到相同的值然后它应该与task_chapter_name
排序。
答案 0 :(得分: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);
答案 1 :(得分:0)
提取列并按顺序对它们进行排序,最后对原始数组进行排序。显然,您可以将SORT_ASC
或SORT_DESC
用于不同订单的不同数组:
array_multisort(array_column($task_array, 'task_chapter_name'),
array_column($task_array, 'task_name'),
$task_array);
{p <1}}需要PHP&gt; = 5.5.0或使用PHP Implementation of array_column()。或者你可以遍历并构建数组,以便在上面的排序中使用:
array_column()