简体   繁体   English

PHP数组搜索和操作

[英]PHP array search and manipulation

<?php
     include 'database.php';
     $sql="SELECT `j_company`,`j_salary`,`j_title` FROM `jobs`";
     $query=mysqli_query($conn, $sql);
     if(!$query)
     {
     echo "<h1>Unsuccessful</h1>";
     echo("Error description: " . mysqli_error($conn));
     }
     $arr=array();
     while ($fetch=mysqli_fetch_assoc($query))
     {
     $arr[]=$fetch;
     }
?>

As above i am retrieving j_company, j_title, j_salary, from the 'jobs' table. 如上所述,我从“工作”表中检索j_company,j_title,j_salary。

After that i need to search the array arr[] foreach company, to find all the job titles (j_title), if there are more than one SAME j_title - find the average of the salaries under the same j_title, and possibly store the j_company, j_title, j_salary(average for each same job title) in an array. 之后,我需要搜索每个公司的数组arr [],以查找所有职位(j_title),如果有多个相同的j_title-查找相同j_title下的薪水平均值,并可能存储j_company,数组中的j_title,j_salary(每个相同职位的平均值)。

ex- 
company1   title1   $1000 
company1   title1   $1500 

company2   title2   $2000 
company2   title3   $2500 

company3   title3   $3000 
company3   title3   $2500 

output - 

company1   title1   $1250 

company2   title2   $2000 
company2   title3   $2500 

company3   title3   $2750 

Try this simple foreach 试试这个简单的foreach

$reuslSetArray = array();
if (!is_null($arr)) {
    foreach ($arr as $key => $mainArray) {
        $reuslSetArray[$mainArray['j_company'] . '_' . $mainArray['j_title']][] = $mainArray['j_salary'];
    }
}

if (!is_null($reuslSetArray)) {
    foreach ($reuslSetArray as $key => $resultArray) {
        $labels = explode("_", $key);
        $value = array_sum($resultArray) / count($resultArray);
        echo $labels[0] . ' ' . $labels[1] . ' ' . $value . " <br>";
    }
}

If you don't need to use every single row, then you can do it all via SQL: 如果您不需要使用每一行,则可以通过SQL完成所有操作:

SELECT j_company,j_title,COUNT(*) as c, SUM(j_salary) as s FROM table GROUP BY j_company, j_title

With the result of the query in $row , 查询结果在$row

$avg = $row['s'] / $row['c'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM