我还是非常新的PHP,所以我想知道我是否能得到一些帮助?我应该通过使用带有foreach循环的while循环遍历关联数组来创建图表。但我一直在无限循环,我不完全确定如何解决它。我也怀疑if声明条件没有帮助,但我也不知道。我错过了什么,有更好的方法来解决这个问题吗?
以下是有问题的代码:
<?php
include 'davesinventory.php';
$delimiter = " \n";
$inventory['name'] = rtrim(strtok($data, $delimiter));
$inventory['year'] = rtrim(strtok($delimiter));
$inventory['serial'] = rtrim(strtok($delimiter));
$inventory['seats'] = rtrim(strtok($delimiter));
$inventory['charge'] = rtrim(strtok($delimiter));
$inventory['days'] = rtrim(strtok($delimiter));
$inventory['rev'] = rtrim(strtok($delimiter));
$inventory['orig'] = rtrim(strtok($delimiter));
$inventory['miles'] = rtrim(strtok($delimiter));
$inventory['deprec'] = rtrim(strtok($delimiter));
$inventory['freq'] = rtrim(strtok($delimiter));
printf("<b> VEHICLE\tYEAR\t SERIAL#\t RENT COST\t DAYS OUT\t REVENUE\t ORIG. PRICE\t MILEAGE\t NOTES\n</b>");
?>
<hr>
<?php
while($inventory['name']){
foreach($inventory as $key => $vehicles){
if ($key !== ['seats'] || ['deprec'] || ['freq'])
{
print $vehicles;
}
else if($key == ['seats'] || ['deprec'] || ['freq'])
{
echo " ";
}
}
}
?>
<pre>
以下是&#39;包含&#39;的文件。要求:
<?php
$data =
"DodgeAvenger 2006 DA111-9 4 35.50 105 3727.50 21297.00 8795 .20 Monthly
Olds_Alero 2004 OA340-1 5 29.95 126 3773.70 23335.00 36010 .20 Monthly
Chry_PT_Crsr 2003 CPTC-MW2 4 37.95 26 986.70 15405.00 29020 .20 Weekly
Cadillac_Limo 1999 1999-01 18 142.50 4 570.00 38900.00 187419 .10 Weekly
Chev_M_Carlo 1997 CMC-21 6 27.30 55 1501.50 19437.50 113689 .20 Monthly
Chev_Suburban 1997 CSB-011 8 42.75 17 726.75 29999.00 137560 .20 Monthly
VW_Bus_T2A 1977 VWB-09 32 15.00 16 240.00 12000.00 397800 NA Daily
Ford_Stn_Wgn 1976 FSW-67 8 10.95 6 65.70 9899.00 149379 NA Whenever
Toy_Forklift 1997 6FGCU-45 1 61.25 65 3981.25 8795 732 .10 Yearly
Cat_Dozer(D7H) 1989 1989-11 1 98.00 5 490.00 67850.00 1304 .10 Yearly
";
?>
答案 0 :(得分:2)
此处无需使用while
循环。 Foreach
就足够了
<?php
if(isset($inventory['name'])){
foreach($inventory as $key => $vehicles){
if ($key !== 'seats' || $key !=='deprec' || $key !=='freq')
{
print $vehicles;
}
else{
echo " ";
}
}
}
?>
答案 1 :(得分:1)
Blank's answer应该适合你。我的实际应该是一个评论,但在答案中格式化代码要容易得多。
如果使用while
只是一个恼人的要求进行家庭作业或测试(根据你的评论...),你可以简单地解决它:
$finished = false;
while (!$finished)
{
//do all the work here - foreach loop and so on
$finished = true;
}