如何获取单行中多列的最大值?

时间:2019-11-02 19:13:12

标签: mysql database laravel

试图在单行中获取月份列的最大值

例如,我想从第一列的jan〜dec中获取最大值,当前为5是最大值

最好在laravel中做

enter image description here

1 个答案:

答案 0 :(得分:1)

请参见PHP max函数

要获取月份名称(记住一个月以上可以有最大值),您需要实现一个循环。

$max_day = max(
    $record->jan,
    $record->feb,
    $record->mar,
    $record->apr,
    $record->may,
    $record->jun,
    $record->jul,
    $record->aug,
    $record->sep,
    $record->oct,
    $record->nov,
    $record->dec
);

$columns = [
    'jan' => 'January',
    'feb' => 'February',
    'mar' => 'March',
    'apr' => 'April',
    'may' => 'May',
    'jun' => 'June',
    'jul' => 'July',
    'aug' => 'August',
    'sep' => 'September',
    'oct' => 'October',
    'nov' => 'November',
    'dec' => 'December',
];

$max_months = [];

foreach ($columns as $column_name => $month_name) {
    if ($record->{$column_name} === $max_day) {
        $max_months[] = $month_name;
    }
}

// $max_months e.g. ['January', 'February']