带有if语句的foreach循环中的number_format

时间:2015-01-13 18:00:11

标签: php numbers format

我有三列数据来自表单。我的目标是如果字段留空,则为每个条目添加小数位。例如,我有BMI,身高和体重。如果表单字段留空,则BMI将有一个小数位,结果为0.0。对于重量,它将为0.00,依此类推。

以下是我现在处理BMI表单字段的代码:

$return['is_spouse'] = ($return['is_spouse'] == 1) ? 'Yes' : 'No';
    if($biometric_data) {
        foreach(self::$biometric_fields as $column_name) {
            if($column_name == 'bmi') {
                $biometrics[$column_name] = number_format($bio[$column_name], 1);
                continue;
            }
            $biometrics[$column_name] = $bio[$column_name];
        }
    }

当尝试将高度或重量部分添加到代码中时,BMI变为空白结果,数字格式仅应用于高度,就像跳过代码的该部分一样。

$return['is_spouse'] = ($return['is_spouse'] == 1) ? 'Yes' : 'No';
    if($biometric_data) {
        foreach(self::$biometric_fields as $column_name) {
            if($column_name == 'bmi') {
                $biometrics[$column_name] = number_format($bio[$column_name], 1);
                continue;
            }
            $biometrics[$column_name] = $bio[$column_name];
        }
    }

    $return['is_spouse'] = ($return['is_spouse'] == 2) ;
    if($biometric_data) {
        foreach(self::$biometric_fields as $column_name) {
            if($column_name == 'height') {
                $biometrics[$column_name] = number_format($bio[$column_name], 2);
                continue;
            }
            $biometrics[$column_name] = $bio[$column_name];
        }
    }

1 个答案:

答案 0 :(得分:1)

你有两个foreach循环,所以在第二个循环中它会重置' bmi'字段运行时:

$biometrics[$column_name] = $bio[$column_name];

您需要将两个循环合并为一个:

foreach(self::$biometric_fields as $column_name) {
        if($column_name == 'height') {
            $biometrics[$column_name] = number_format($bio[$column_name], 2);
            continue;
        } else if($column_name == 'bmi') {
            $biometrics[$column_name] = number_format($bio[$column_name], 1);
            continue;
        }
        $biometrics[$column_name] = $bio[$column_name];
    }