我需要打印月份名称,然后打印相应数组值的每月费用(1 = jan,2 = feb ...等)。我已经相当远了,可以打印"月[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);
答案 0 :(得分:1)
使用每月包含的数组效率更高:
$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]);
答案 1 :(得分:0)
您可以为月份名称添加另一个数组(因为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]);
}
答案 2 :(得分:0)