簡體   English   中英

如何訪問多維數組元素以使其相乘

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

創建一個多維數組,其中包含運輸公司可能用來確定盒子體積的幾個盒子的尺寸(以英寸為單位),但我無法訪問我想要的元素。 我只需要將長度寬度和深度的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)您似乎在foreach循環中覆蓋了$boxArray變量

2) 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]引用字符串“ Medium Box”

4) $boxArray[3,0]不是正確的鍵引用,將返回null

“小盒子”,“中盒子”,“大盒子”應該是陣列鍵嗎?

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

我感覺到您的意思是:

$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>'; 
    }

如果您的陣列格式正確:

    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