我需要为相应的数组值(1=jan, 2=feb…等)打印月份名称和每月费用。例如,我可以打印"Month[1] $2997.10",但不知道如何以"Jan $2997.10"的格式打印它。我知道我错过了一些简单的东西,但我已经尝试了我能想到的所有方法,但只得到错误消息。提前感谢您的帮助。
$monthly_expense = array( '1' => 2997.10,
'2' => 921.00,
'3' => 371.99,
'4' => 1928.00,
'5' => 1206.00,
'6' => 10190.33,
'7' => 8390.35,
'8' => 3009.93,
'9' => 4803.30,
'10'=> 1212.30,
'11'=> 225.90,
'12'=> 594.65
);
//Your program starts here!
switch ($monthly_expense) {
case 1:
$month = 'Jan';
break;
case 2:
$month = 'Feb';
break;
case 3:
$month = 'Mar';
break;
case 4:
$month = 'Apr';
break;
case 5:
$month = 'May';
break;
case 6:
$month = 'Jun';
break;
case 7:
$month = 'Jul';
break;
case 8:
$month = 'Aug';
break;
case 9:
$month = 'Sep';
break;
case 10:
$month = 'Oct';
break;
case 11:
$month = 'Nov';
break;
case 12:
$month = 'Dec';
break;
default:
$month = 'Not a valid month!';
break;
}
for ($count = 1; $count < sizeof($monthly_expense)+1; $count++)
printf ("Month [%d]: $%.2f'n", $monthly_expense[$count]);
//Compute the total of all salaries
$totalExpense = 0.0;
foreach ($monthly_expense as $value)
$totalExpense += $value;
printf ("The total company expenses for the year is $%.2f.'n", $totalExpense);
像这样使用包含每个月的数组会更有效:
$months = array(1 => 'Jan.', 2 => 'Feb.', 3 => 'Mar.', 4 => 'Apr.', 5 => 'May', 6 => 'Jun.', 7 => 'Jul.', 8 => 'Aug.', 9 => 'Sep.', 10 => 'Oct.', 11 => 'Nov.', 12 => 'Dec.', 13=>'Total');
for ($count = 1; $count < sizeof($monthly_expense)+1; $count++)
printf("%s $%.2f <br>", $months[$count], $monthly_expense[$count]);
您可以为月份的名称添加另一个数组(因为switch
语句看起来很糟糕):
$months = array(
'undefined', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dic'
);
然后:
for ($i = 1; $i <= count($monthly_expense); $i++) {
printf ("Month [%s]: $%.2f'n", $months[$i], $monthly_expense[$i]);
}
您不需要月份数组,只需使用date和mktime从$monthly_expense
数组中的键获取月份:
foreach( $monthly_expense as $month => $value ) {
printf( "Month [%s]: $%.2f'n", date("M", mktime(0, 0, 0, $month, 1) ), $value );
}