douxi2011 2014-03-20 14:59
浏览 30
已采纳

如何排序php数组的字符串索引

I am interested to sort php array index key in ascending order,

I have this array

 (
[462 1 5.300] => 1
[462 9 4.900] => 1
[462 9 4.300] => 1
[462 2 4.800] => 1
[462 6 4.700] => 1
[462 7 4.900] => 1
[462 7 4.700] => 1
[462 8 4.500] => 1
[462 3 4.500] => 1
[462 4 4.700] => 1
[462 3 4.700] => 1
[462 5 4.500] => 1
)

I expect output to be like this after sort

(
[462 1 5.300] => 1
[462 2 4.800] => 1
[462 3 4.500] => 1
[462 3 4.700] => 1
[462 4 4.700] => 1
[462 5 4.500] => 1
[462 6 4.700] => 1
[462 7 4.700] => 1
[462 7 4.900] => 1
[462 8 4.500] => 1
[462 9 4.300] => 1
[462 9 4.900] => 1
)

I want to sort first 3 index which is used as string is it possible ? I have 3 more column in array but I am showing only 3 columns here..

  • 写回答

3条回答 默认 最新

  • dongli2000 2014-03-20 15:08
    关注

    A normal ksort() can do the trick, but if the sorting is to be performed in multiple orders (different orders for different parameter values), this wouldn't work.

    You can achieve this with array_multisort(). First you create three (or more, depending on the number of parameters you have) arrays - each containing the parameter values. Then simply pass it to array_multisort() with the corresponding sort flag:

    $param1 = $param2 = $param3 = array();
    
    foreach ($data as $key => $value) {
        $parts = explode(' ', $key);
        $param1[] = $parts[0];
        $param2[] = $parts[1];
        $param3[] = $parts[2];
    }
    
    array_multisort($data, $param1, SORT_ASC, $param2, SORT_ASC, $param3, SORT_ASC);
    

    If you want the sorting to be performed in descending order, then you can use SORT_DESC instead. See the documentation for a list of available sort flags.

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下