donvo24600 2014-09-08 05:36
浏览 22
已采纳

php按字母顺序排列多维数组

I have a multidimensional array that is created with this:

for($i=0; $i<count($sub_results);$i++)
{
    $presenters = array(
        'first_name' => $sub_results[$i]['data'][1]['user_value'],
        'last_name' => $sub_results[$i]['data'][2]['user_value'],
        'preferred_name' => $sub_results[$i]['data'][8]['user_value'],
        'organisation' => $sub_results[$i]['data'][11]['user_value'],
        'portraitFile' => $portrait_file_path.$portrait,
        'Abstract1title' => $sub_results[$i]['data'][19]['user_value'],
        'Abstract1accepted' => $sub_results[$i]['data'][18]['user_value'],
        'Abstract1synopsis' => $sub_results[$i]['data'][22]['user_value'],
        'Abstract1format' => $sub_results[$i]['data'][26]['user_value'],
        'Abstract1coauthors' => $sub_results[$i]['data'][20]['user_value'],
        'Abstract2title' => $sub_results[$i]['data'][28]['user_value'],
        'Abstract2accepted' => $sub_results[$i]['data'][27]['user_value'],
        'Abstract2synopsis' => $sub_results[$i]['data'][31]['user_value'],
        'Abstract2format' => $sub_results[$i]['data'][30]['user_value'],
        'Abstract2coauthors' => $sub_results[$i]['data'][29]['user_value']
    );
}

I want to sort the resulting array alphabetically by last_name. How is this achieved?

With thanks in advance, emrys

  • 写回答

1条回答 默认 最新

  • dongnius85154 2014-09-08 06:01
    关注

    This should do it for you. It's case-insensitive. If you have any questions about how it works let me know. Remember that usort accepts the array by reference, meaning that if you want to preserve the original array you will need to make a copy of it.

    <?php
        usort($array,function($a,$b) {
            $comparison = strcasecmp($a['last_name'],$b['last_name']);
            if ($comparison == 0) return 0;
            return ($comparison < 0) ? -1 : 1;
        });
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?