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



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

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

提取列并按顺序排序,最后对原始数组进行排序。显然,您可以为不同的数组使用SORT_ASCSORT_DESC,用于不同的顺序:

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

PHP>= 5.5.0,或者使用PHP实现array_column()。或者您可以循环并构建数组以在上面的排序中使用:

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

相关内容

  • 没有找到相关文章

最新更新