PHP按二维数组中的键排序数组

时间:2016-08-30 17:11:43

标签: php arrays sorting multidimensional-array

在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排序。

2 个答案:

答案 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_ASCSORT_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()