doulang7699 2018-07-03 10:15
浏览 262

如何按自定义顺序对数组进行排序

I have an array, and I would like to out put value on specific order. How I can do this.

Array

$age = array(48,37,43,56,32);

Output I want

37
56
43
32
48

I have put array $age in foreach loop. I created another array outside foreach loop. I am doing array Push if the the value = xx. Its not working.

What is the best way so I can have my result coming out in above order.

  • 写回答

1条回答 默认 最新

  • dongnachuang6635 2018-07-03 11:03
    关注

    I'm not sure, I understand your question correctly but if you already know the order than what's the purpose of making this array.

    Well, I guess I have two solutions to sort this array in your custom order

    Option 1

    Specify $order array (if it's already known to you) and use usort to compare the values of $age and $order arrays. usort will find the items of $age within the $order array.

    $order = array(37, 56, 43, 32, 48);
    $age = array(48, 37, 43, 56, 32);
    
    usort($age, function ($a, $b) use ($order) {
        $firstItem  = array_search($a, $order);
        $secondItem = array_search($b, $order);
    
        return $firstItem - $secondItem;
    });
    
    print_r($age);
    

    I've used closure in usort to make sorting simpler

    Output

    Array
    (
        [0] => 37
        [1] => 56
        [2] => 43
        [3] => 32
        [4] => 48
    )
    

    You can check usort and array_search

    Option 2

    From your comment, I tried to come up with another approach which is setting the keys in $age and $order arrays and compare both arrays to sort it in custom order.

    $order = array('students', 'adults', 'disable', 'enable', "variable");
    $age = array(
        'variable' => 48,
        'students' => 37,
        'disable' => 43,
        'adults' => 56,
        'enable' => 32
    );
    
    $ordered_array = array_merge(array_flip($order), $age);
    print_r($ordered_array);
    

    Output

    Array
    (
        [students] => 37
        [adults] => 56
        [disable] => 43
        [enable] => 32
        [variable] => 48
    )
    

    Also check array_merge and array_flip

    评论

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突