dougaimian1143 2019-03-14 14:33
浏览 49
已采纳

Php无法正确排序数组

I have array:

$test['name1'][256]=[
        'lead_data'=>[
            'datum_event'=>'13.03.2019',
            'address'=>'addr1'
        ]
    ];
    $test['name1'][257]=[
        'lead_data'=>[
            'datum_event'=>'12.02.2019',
            'address'=>'addr2'
        ]
    ];
    $test['name2'][259]=[
        'lead_data'=>[
            'datum_event'=>'15.03.2019',
            'address'=>'addr4'
        ]
    ];
    $test['name2'][260]=[
        'lead_data'=>[
            'datum_event'=>'10.03.2019',
            'address'=>'addr5'
        ]
        ];

    $test['name2'][261]=[
        'lead_data'=>[
            'datum_event'=>'10.02.2019',
            'address'=>'addr10'
        ]
    ];

I need sort groups 'name1' and 'name2' by the smallest 'datum_event' value . So group 'name2' must be first, bacuse there is the smallest datum_event = '10.02.2019' . Also need sort inner arrays by datum_event (from smallest ti heighest). My code is:

function getMinDate($e) {
        return min(array_column(array_column($e, "lead_data"), "datum_event"));
    }

uasort($test, function ($a, $b) {return strcmp(getMinDate($b), getMinDate($a));});

foreach($test as &$e) {
            uasort($e, function ($a, $b) {
                return strcmp($a['lead_data']['datum_event'], $b['lead_data']['datum_event']);});
        }

By i cant get correct output, group 'name2' is second, but must be first. Please , how can i solve this?

  • 写回答

1条回答 默认 最新

  • duanhui1869 2019-03-14 14:57
    关注

    Your dates are strings that are not in a sortable format, so you'll need to convert all of them into something sortable before the sort will work. d.m.Y will not sort properly, but if you convert them to Y-m-d format or timestamps it will work. I think it will be more efficient to do this once before you sort rather than repeatedly within the comparison function. So pre-process the name* arrays to determine the minimum date.

    foreach ($test as $name => $leads) {
        $test[$name]['min_date'] = min(array_map(function($lead){
            return date_create($lead['lead_data']['datum_event'])->format('U');
        }, $leads));
    }
    

    Then sort by that new key.

    uasort($test, function($a, $b) {
        return $a['min_date'] <=> $b['min_date'];
    });
    

    You can remove the sort key after sorting if you need to.

    foreach ($test as $name => $leads) {
        unset($test[$name]['min_date']);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛