我正在尝试计算每个盒子的体积,但我不断遇到错误,我不知道如何解决它。一切似乎都是正确的,我按照这本书的例子来说。
这是它在此代码中给出的错误:
“注意:未定义的偏移量:在第16行的C:\ wamp \ www \ BoxArray.php中为0”
<?php
$BoxMeasurements = array("sBox" => array("length" => 12, "width" => 10, "depth" => 2.5),
"mBox" => array("length" => 30, "width" => 20, "depth" => 4),
"lBox" => array("length" => 60, "width" => 40, "depth" => 11.5));
$BoxMeasurements = array_slice($BoxMeasurements, 0, 3);
echo "The box sizes are:";
for($i = 0; $i < count($BoxMeasurements); ++$i)
{
echo "$BoxMeasurements[$i]";
}
?>
当我尝试这样做时,我得到了这个错误:
“解析错误:语法错误,意外'=',期待')'在第8行的C:\ wamp \ www \ BoxArray.php”
<?php
$sBox = array("length" => 12, "width" => 10, "depth" = 2.5);
$mBox = array("length" => 30, "width" => 20, "depth" = 4);
$lBox = array("length" => 60, "width" => 40, "depth" => 11.5);
$dimension = array($sBox, $mBox, $lBox);
echo "$dimension[0][0]";
?>
是否有一种特殊的方法来调用变量/数组名称?
答案 0 :(得分:2)
$BoxMeasurements
被声明为关联数组,这意味着您应该使用您在声明中定义的键来访问其值:"sBox"
,"mBox"
和"lBox"
。< / p>
为了迭代这种数组,您可以使用foreach
形式:
<?php
$BoxMeasurements = array("sBox" => array("length" => 12, "width" => 10, "depth" => 2.5),
"mBox" => array("length" => 30, "width" => 20, "depth" => 4),
"lBox" => array("length" => 60, "width" => 40, "depth" => 11.5));
echo "<pre>";
echo "The box sizes are:\n";
foreach($BoxMeasurements as $name => $size)
{
$volume = $size['length'] * $size['width'] * $size['depth'];
echo " - $name: $volume\n";
}
echo "</pre>";
?>
输出
The box sizes are:
- sBox: 300
- mBox: 2400
- lBox: 27600
答案 1 :(得分:0)
您似乎无法理解变量名称和变量内容之间的区别,如围绕名称使用"
所示。这毫无意义。它应该是
echo $BoxMeasurements[$i];
在分配数组时,正确的语法是:
key => value
而你的一些&#34;行&#34;只分配&#34; key = value&#34;这会引发语法错误。
此外,您尝试通过数字索引访问数组,而您的数组不使用它们。使用foreach迭代数组:
foreach( $BoxMeasurements as $key=>$val ) {
echo $val;
}
最后,您应该在for
循环中执行增量后,而不是预增量。
我强烈建议花一些时间并通过一些教程,因为你犯了太多基本错误。