联想"多维"排列

时间:2015-11-02 01:32:34

标签: php arrays multidimensional-array

大家好,我有一个简短的问题,我希望你们中的一个人能回答。我正在使用多维数组,我应该声明一个小,中,大盒子的宽度,长度和深度,然后添加显示每个盒子的体积的语句。我的问题来自于声明(我是PHP的新手)。在WAMP上运行脚本时,我返回一个空白页面,所以我猜我做错了什么。这是代码,感谢您提供任何有用的答案。

<?php
$SmallBox =array("length" =>12, "width" =>10, "depth" =>2.5);
$MediumBox =array("length" =>30, "width" =>20, "depth" =>4);
$LargeBox =array("length" =>60, "width" =>40, "depth" =>11.5);
echo $SmallBox ["length"]["width"] ["depth"];
echo $MediumBox ["length"] ["width"] ["depth"];


?>

3 个答案:

答案 0 :(得分:1)

您定义的数组是一维关联数组。

您应该在此方法中定义框数组:

// I've separated them into lines for easier readability
$boxes = array(
    "small" => array("length" =>12, "width" =>10, "depth" =>2.5),
    "medium" => array("length" =>30, "width" =>20, "depth" =>4),
    "large" => array("length" =>60, "width" =>40, "depth" =>11.5)
);
// Show the structure and contents of the array
echo '<h2>Array Structure</h2>';
print_r($boxes);

// You will have to access these elements individually
// Small box:
echo '<h2>Small Box</h2>';
echo 'Length: '.$boxes['small']["length"].'<br>';
echo 'Width: '.$boxes['small']["width"].'<br>';
echo 'Depth: '.$boxes['small']["depth"].'<br>';
echo 'Volume: '.$boxes['small']["length"]*$boxes['small']["width"]*$boxes['small']["depth"].'<br>';

// Medium box:
echo '<h2>MediumBox</h2>';
echo 'Length: '.$boxes['medium']["length"].'<br>';
echo 'Width: '.$boxes['medium']["width"].'<br>';
echo 'Depth: '.$boxes['medium']["depth"].'<br>';
echo 'Volume: '.$boxes['medium']["length"]*$boxes['medium']["width"]*$boxes['medium']["depth"].'<br>';

答案 1 :(得分:0)

使用print_r($ SmallBox),这假设显示警告&#39;因为echo不能接受数组,打开php的错误报告,

如果您希望将其格式化:

    print "<pre>";
    print_r($SmallBox);
    print "</pre>";
    exit;   

了解数据类型和长度使用var_dump($ SmallBox)

打开错误报告,请参阅此帖子:How do I get PHP errors to display?

答案 2 :(得分:-1)

虽然你已经正确地创建了数组,但你的回声语句不可能这样。

尝试:

echo $SmallBox["length"];
echo $SmallBox["width"];
echo $SmallBox["depth"];

等等。