简体   繁体   中英

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.

    <!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

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];

3) $boxArray[1][0] references a string "Medium Box"

4) $boxArray[3,0] isn't a correct key reference and would return 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]; 
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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