php - 条件后如何从多维数组中获取工资总和
问题描述
在这个项目中,我有一个多维数组,其中保留了一些员工的姓名、职位、专业和薪水。我需要从数组中找到所有经理和所有员工的平均工资。
<!DOCTYPE html>
<html>
<head>
<meta sharset="UTF-8"/>
<title>Project3</title>
</head>
<body>
<?php
$employees = array(array("name" => "Nikolaou Nikolaos",
"occupation" => "Employee",
"salary" => 1500,
"specialty" => "Web Programmer"),
array("name" => "Papadopoulou Anna",
"occupation" => "Manager",
"salary" => 2300,
"specialty" => "Human resources management"),
array("name" => "Alexiou Nikoleta",
"occupation" => "Employee",
"salary" => 800,
"specialty" => "Secretary"),
);
//Start of the function that prints the arrays in a specific way.
function printTable($table)
{
foreach ($table as $employee => $list) {
// Print a heading:
echo "<h2 style=\"text-align:left; font-size:26px; font-family:times new roman; color:blue\">Employee #$employee</h2><ul>";
// Print each district data:
foreach ($list as $key => $value) {
echo "<li style=\"text-align:left; font-size:18px; font-family:times new roman; color:black\">$key: $value</li>\n";
}// End of nested FOREACH.
// Close the list:
echo '</ul>';
} // End of main FOREACH.
}// End of the function.
//function that calculates and returns the average salary of employees and managers separately.
function calcMeanAges($table, &$hmean, &$gmean)
{
$cEmployees = 0;
$sumsalary_e = 0;
$cManagers = 0;
$sumsalary_m = 0;
foreach ($table as $occupation =>$list) {
foreach ($list as $salary =>$value) {
if ($occupation == "Employee") {
$cEmployees++;
$sumsalary_e += $salary['salary'];
}
if ($occupation == "Manager") {
$cManagers++;
$sumsalary_m += $salary['salary'];
}
}
}
$hmean = $sumsalary_e / $cEmployees;
$gmean = $sumsalary_m / $cManagers;
}
//call of the function that calculates the average salaries.
calcMeanAges($employees, $h, $g);
echo "$h<br>";
echo "$g";
//Printing the elements of the arrays
echo '<p style="color:red;font-size:28px;font-family:times new roman;"><b>Employees and managers</b></p><br>';
printTable($employees);
?>
</body>
</html>
我需要分别计算员工和经理的平均工资。所以我想在其中设置一个条件Foreach()
来检查谁是谁,然后计算他们并保留他们的工资总和。但它不能正常工作。我会很感激一些帮助。
解决方案
在这种情况下,您只需要一个循环而不是 2,那么您要检查或 dd up 的所有出现都是内部数组的成员
function calcMeanAges($table, &$hmean, &$gmean)
{
$cEmployees = 0;
$sumsalary_e = 0;
$cManagers = 0;
$sumsalary_m = 0;
foreach ($table as $item) {
if ($item['occupation'] == "Employee") {
$cEmployees++;
$sumsalary_e += $item['salary'];
}
if ($item['occupation'] == "Manager") {
$cManagers++;
$sumsalary_m += $item['salary'];
}
}
$hmean = $sumsalary_e / $cEmployees;
$gmean = $sumsalary_m / $cManagers;
}
推荐阅读
- oracle - 确定 Oracle 数据库中表/视图的最后使用日期
- algorithm - 带有 if-else 语句的 for 循环的大哦
- linq - MVC Linq .Random() 语法错误
- python - 使用python根据特定条件将csv文件划分为垃圾
- java - 如何解决异常类 java.util.HashMap$Values 无法转换为 HashMap 中的类 java.util.Enumeration
- python - 将升序序列号字段添加到集合中的所有现有 mongodb 文档
- firebase - Flutter:如何将firebase uid设置为用户文档ID?
- spring-boot - 如果在我们正在测试的方法中使用新关键字声明实例,我们可以模拟它吗?
- powershell - 将 powershell 导出到 CSV 的问题
- c - 在C中将结构添加到结构链表中