Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/228.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将答案相乘并返回它的数组_Php_Arrays - Fatal编程技术网

Php 将答案相乘并返回它的数组

Php 将答案相乘并返回它的数组,php,arrays,Php,Arrays,这就是我想做的。我希望我的代码返回以下内容: “这个小盒子的体积是:300” 但我似乎不知道该怎么办: <?php $box = array( "Small box" => array("length" => 12, "width" => 10, "depth" => 2.5), "Medium box" => array("length" => 30, "width" => 20, "depth" =>

这就是我想做的。我希望我的代码返回以下内容:

“这个小盒子的体积是:300”

但我似乎不知道该怎么办:

<?php
    $box = array(
       "Small box" => array("length" => 12, "width" => 10, "depth" => 2.5),
       "Medium box" => array("length" => 30, "width" => 20, "depth" => 4),
       "Large box" => array("length" => 60, "width" => 40, "depth" => 11.5)

    );
    foreach ($box as $number => $boxes)
    {
        echo "The volume of the "."$number"." is: \t";
        foreach ($boxes as $value)            
        {
            if (is_numeric($value))
            {
               $sum = array_product($boxes);
               echo "$sum";
            }
        }
        echo "<br />";
    }
    ?>

您正在通过
$value
循环,计算并显示
$sum
多次。只需计算产品:

foreach ($box as $number => $boxes)
{
    echo "The volume of the "."$number"." is: \t";
    echo array_product($boxes);

    echo "<br />";
}

您可以将框的大小放入索引数组中

 $sum = 1;/*set variable sum to 1 so if it's * in another numerics it's not 0*/
 $i = 0; /*set i condition to reset value of condition*/
    foreach ($box as $number => $boxes) { 
        foreach ($boxes as $value)            
        {
            if (is_numeric($value)){
               $sum = $sum*$value; /*it's product length*width*depth */
            }
            /*cek the condition if count of boxes is limit lengt so define variable data["box type"]*/
            if(($i+1) == count($boxes)){
              $data[$number] = $sum; /*give value for $data["box type"]*/
            }
            $i++;
        }
        $sum = 1;/*reset sum to 1*/
        $i   =0;/*reset i to 0*/
    }
这是打印(数据)的结果

您可以使用访问任何类型的框的变量

echo "sample : The volume of the Medium Box is ". $data["Medium box"]." : \t";
结果会是这样

sample : The volume of the Medium Box is 2400

如果您正在寻找,请告诉我。

$code>$sum=array\u product($box)使用了错误的变量use
$sum*=$value但不
$sum=1位于foreach上方。和
回显“$sum”然后应该在foreach之后。非常感谢您的解决方案!!!它显然有效。谢谢你这样的解释,我理解代码的作用。这确实有效,谢谢你的解释,现在我明白我做错了什么。
Array
(
    [Small box] => 300
    [Medium box] => 2400
    [Large box] => 27600
)
echo "sample : The volume of the Medium Box is ". $data["Medium box"]." : \t";
sample : The volume of the Medium Box is 2400