dsy19811981 2017-11-16 18:59
浏览 24
已采纳

按子阵列类型值排序,然后按字母顺序排序

I have an array that looks something like this:

$array = [
    'field1' => [
        '#type' => 'text',
        '#label' => 'Field 11',
    ],
    'field4' => [
        '#type' => 'fieldset',
        '#label' => 'Field 4',
    ],
    'field12' => [
        '#type' => 'text',
        '#label' => 'Field 12',
    ],
    'field3' => [
        '#type' => 'fieldset',
        '#label' => 'Field 3',
    ],
    'field18' => [
        '#type' => 'text',
        '#label' => 'Field 18',
    ],
];

I would like to sort this array in such a way where all the fields of type fieldset are at the bottom. At the same time, I would like the text fields (which are on top) to be sorted alphabetically by the #label and the fieldsets (which should be at the bottom) should also be sorted alphabetically by the label. This is what I had so far.

ksort($array);
uasort($array, function($field1) {
    if ($field1['#type'] !== 'fieldset') {
        return 0;
    }
    return 1;
});

Sorting the array by the key value successfully sorts my entire array alphabetically. But once I add the uasort, although my fieldset's are at the bottom, the alphabetical order is no longer present.

Any ideas?

  • 写回答

2条回答 默认 最新

  • doulouli8686 2017-11-16 19:17
    关注

    Use usort with 2 conditions

     usort($array, function ($i1, $i2) { 
                     // compare types 
                     $r = ($i1['#type'] == 'fieldset' ? 1 : 0) -  ($i2['#type'] == 'fieldset' ? 1 : 0); 
                     // if both are (or not) fieldset (r == 0), compare labels
                     return $r ? $r : strcmp($i1['#label'], $i2['#label']);  } );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探