使用PHP中的数组值进行计算

时间:2018-09-21 06:28:50

标签: php arrays loops if-statement

如果我有一个多维数组,如何使数组中的某些组(例如:'wages','hrs')插入某个公式中,成为$ x,这样它就可以通过下面的ifelse语句?

我正在使用以下一般功能计算月薪: ($employees[0]['wage']) * ($employees[0]['hrs']) * 4 但是,我想知道如何格式化第一个方括号(key?)$employees[ _ ],以便数组在'hrs'和'wage'值下的每个值都可以计算出每个$ x的值。数组中的雇员(有9个)。我假设我将创建一个循环,但是如何填充括号以实现这一目标呢?

 with monthly salary = ($employees[_]['wage']) * ($employees[_]['hrs']) * 4
 where $employees is a pre-set multidimensional array I created.

<?php 

   $x = __

    if ( $x >= 3000 ) { 
      echo "High paying"; 
     } elseif ( 2000 =< x =< 2999 ) {
        echo "Good paying";
     } else {
      echo "Low paying"; 
     } 
?>  

3 个答案:

答案 0 :(得分:3)

您应该使用此

 $x = array();

for($i=0;$i<count($x);$i++)
{
    if ( $x[$i] >= 3000 ) 
    { 
      echo "High paying"; 
    } 
    elseif ( 2000 >= $x[$i] <= 2999 ) 
    {
       echo "Good paying";
    } 
    else 
    {
      echo "Low paying"; 
     } 
}

答案 1 :(得分:1)

我认为您只希望一个foreach循环遍历$employees数组中的每个员工:

foreach ($employees as $employee) {
    $x = $employee['wage'] * $employee['hrs']) * 4;
    if ( $x >= 3000 ) { 
        echo "High paying"; 
    } elseif ( 2000 =< x =< 2999 ) {
        echo "Good paying";
    } else {
        echo "Low paying"; 
    } 
}

答案 2 :(得分:0)

假设您拥有$employees多维数组;按照下面的代码制作,该代码可以为您提供薪水,是高,低或好的比例。

这是代码;

/**
 * Function to calculate salary scale is high, good, low
 * @param int $salary
 * @return string
 */
function calculateSalaryScale($salary) {
    if ($salary >= 3000) {
        $scale = "High paying";
    } else if (2000 <= $salary && $salary <= 2999 ) {
        $scale = "Good paying";
    } else {
        $scale = "Low paying";
    }

    return $scale;
}

// Assuming your employyees array is like below
$employees = array(
    array('emp_id' => 1, 'name' => 'John Doe', 'wage' => 90, 'hrs'=> 8),
    array('emp_id' => 2, 'name' => 'Lorem Ipsum', 'wage' => 150, 'hrs'=> 6),
    array('emp_id' => 3, 'name' => 'Doler amit', 'wage' => 50, 'hrs'=> 10),
);

foreach ($employees as &$employee) {
    $employee['salary'] = $employee['wage'] * $employee['hrs'] * 4;
    $employee['scale'] = calculateSalaryScale($employee['salary']);
}

echo "<pre>";
print_r($employees);
exit;

它将为您提供以下输出;

Array
(
    [0] => Array
        (
            [emp_id] => 1
            [name] => John Doe
            [wage] => 90
            [hrs] => 8
            [salary] => 2880
            [scale] => Good paying
        )

    [1] => Array
        (
            [emp_id] => 2
            [name] => Lorem Ipsum
            [wage] => 150
            [hrs] => 6
            [salary] => 3600
            [scale] => High paying
        )

    [2] => Array
        (
            [emp_id] => 3
            [name] => Doler amit
            [wage] => 50
            [hrs] => 10
            [salary] => 2000
            [scale] => Good paying
        )

)

然后可以相应地进一步处理$employees数组。