简体   繁体   English

如何访问多维数组元素以使其相乘

[英]How To Access Multidimensional Array Elements to Multiply Them

Create a multidimensional array that contains the measurements, in inches, for several boxes that a shipping company might use to determine the volume of a box.I am having trouble accessing the elements that I actually want. 创建一个多维数组,其中包含运输公司可能用来确定盒子体积的几个盒子的尺寸(以英寸为单位),但我无法访问我想要的元素。 I just need to multiple the 3 integers from length width and depth. 我只需要将长度宽度和深度的3个整数相乘即可。

    <!DOCTYPE html>
<html>
<head>
    <title>DTD and Box Array</title>
</head>
<body>
    <?php
$boxArray = array   (
                    'Small Box' => array(12, 10, 2.5),
                    'Medium Box' => array(30, 20, 4),
                    'Large Box' => array(60, 40, 11.5)
                    );


echo '<table border="1">';
echo '<tr><th>Length</th><th>Width</th><th>Depth</th></tr>';
foreach ($boxArray as $k => $v)
    {
    echo $k.': '.$v[0].' x '.$v[1].' x '.$v[2].' = ' .$v[0]*$v[1]*$v[2].'<br>'; 
    }

    foreach( $boxArray as $boxArray )
{
    echo '<tr>';
    foreach( $boxArray as $key )
    {
        echo '<td>'.$key.'</td>';
    }
    echo '</tr>';
}

// Length * width * depth - dont know how get the integers.
// This echo isnt grabbing the integers i want

// Multiply small box length * width * height


?>

</body>
</html>

1) You seem to be overwriting the $boxArray vaiable in your foreach loop 1)您似乎在foreach循环中覆盖了$boxArray变量

2) echo $boxArray[1][0] , $boxArray[1][0] ,$boxArray[3,0]; 2) echo $boxArray[1][0] , $boxArray[1][0] ,$boxArray[3,0]; isn't correct, you need echo $boxArray[1][0] .','. $boxArray[1][0] .','. $boxArray[3,0]; 是不正确的,您需要echo $boxArray[1][0] .','. $boxArray[1][0] .','. $boxArray[3,0]; echo $boxArray[1][0] .','. $boxArray[1][0] .','. $boxArray[3,0];

3) $boxArray[1][0] references a string "Medium Box" 3) $boxArray[1][0]引用字符串“ Medium Box”

4) $boxArray[3,0] isn't a correct key reference and would return null 4) $boxArray[3,0]不是正确的键引用,将返回null

Should the "Small Box", "Medium Box", "Large Box" be array keys? “小盒子”,“中盒子”,“大盒子”应该是阵列键吗?

ie

$boxArray = array ( "Small Box" => array(12,10,2.5), etc... )

I've got a feeling that what you meant to do is this: 我感觉到您的意思是:

$boxArray = array   (
                    'Small Box' => array(12, 10, 2.5),
                    'Medium Box' => array(30, 20, 4),
                    'Large Box' => array(60, 40, 11.5)
                    );

foreach ($boxArray as $k => $v)
    {
    echo $k.': '.$v[0].' x '.$v[1].' x '.$v[2].' = ' .$v[0]*$v[1]*$v[2].'<br>'; 
    }

If your array is in the correct format: 如果您的阵列格式正确:

    foreach ($boxArray as $v)
    {
    echo $v[0].": ".$v[1].' x '.$v[2].' x '.$v[3].' = ' $v[1]*$v[2]*$v[3]; 
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM