对于具有不同值的数组,我有不同的变量。我需要在HTML中显示每个数组项的值,我已经知道该怎么做了。问题是,我需要找到每个数组项与自身相关的值的百分比。等式将是这样的:
蓝球百分比=蓝球/所有数组项目的总和* 100
我正在寻找一种方法来使用函数来通过该等式回显每个数组项的结果,但不知道如何编写它。
这是我的阵列:
$balls = array(
'red' => 5,
'blue' => 7,
'green' => 2
);
$socks = array(
'red' => 5,
'blue' => 7,
'green' => 2
);
这就是我认为我的HTML应该是这样的:
Blue balls make up<?php echo $percent($ball['blue']); ?>% of the balls.
There are <?php echo $balls['blue']; ?> blue balls.
我试图将此作为最终结果:
Blue balls make up 50% of the balls.
There are 7 blue balls.
我知道底部回声是有效的,但我不知道如何尝试为顶部回声编写函数,或者如果回声本身是可能的。
答案 0 :(得分:0)
<?php
$balls = array(
'red' => 5,
'blue' => 7,
'green' => 2
);
$socks = array(
'red' => 5,
'blue' => 7,
'green' => 2
);
function percent($array, $element)
{
$total = 0;
$elementValue = $array[$element];
foreach($array as $entry)
{
$total += $entry;
}
return ($elementValue / $total) * 100;
}
?>
<html>
<body>
Blue balls make up<?php echo percent($balls, 'blue'); ?>% of the balls.
There are <?php echo $balls['blue']; ?> blue balls.
</body>
</html>
答案 1 :(得分:0)
function percent($getArray,$assocSearch)
{
$total = array_sum($getArray);
$elementVal = $getArray[$assocSearch];
return ($elementVal / $total) * 100;
}
$balls = array(
'red' => 5,
'blue' => 7,
'green' => 2
);
$socks = array(
'red' => 5,
'blue' => 7,
'green' => 2
);
函数调用
Blue balls make up <?php echo percent($balls, 'blue'); ?>% of the balls.
There are <?php echo $balls['blue']; ?> blue balls.
输出
Blue balls make up 50% of the balls.
There are 7 blue balls.
希望这会有所帮助。