PHP常用

## 自定义数组排序
$data = [
    ['id' => 1, 'start_date' => '2016-12-13', 'end_date' => '2017-12'],
    ['id' => 2, 'start_date' => '2015-12-13', 'end_date' => '2018-12'],
    ['id' => 4, 'start_date' => '2018-12-13', 'end_date' => '0000-00'],
    ['id' => 3, 'start_date' => '2012-12-13', 'end_date' => '2015-12'],
    ['id' => 5, 'start_date' => '2016-12-13', 'end_date' => '2019-12'],
];
usort($data, function ($a, $b) {
    if (intval($a['end_date']) == 0) {
        $a['end_date'] = '至今';
    }
    if (intval($b['end_date']) == 0) {
        $b['end_date'] = '至今';
    }
    if ($a['end_date'] == $b['end_date']) {
        return 0;
    }
    // 返回1,将$a排在$b的后面
    return ($a['end_date'] < $b['end_date']) ? 1 : -1;
});

## PHP下Unix时间戳与日期互转(解决1970年前及2038年后问题)
function dateToUnixtime($date, $timezone = 'PRC')
{
    if ($date == 0) {
        $datetime = new DateTime('now', new DateTimeZone($timezone));
    } else {
        $datetime = new DateTime($date, new DateTimeZone($timezone));
    }
    return $datetime->format('U');
}

## laravel whereIn 递归用这个array_merge压缩二维数组压缩为一维数组
if ($type == 1) {
    $merge = array_reduce($array, function($res, $value) {
        return array_merge($res, array_values($value));
    }, []);
} else {
    // 自己直接遍历,实现二维数组压缩为一维数组
    foreach ($array as $key => $value) {
        foreach ($value as $k => $v) {
            $merge[] = $v;
        }
    }
}

你可能感兴趣的:(PHP常用)