<?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.
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.
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
$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:
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
,
$avg = $row['s'] / $row['c'];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.