PHP Getting average grade - php

I need to get the average number of a grade in a function. Doesn't seem to work completly.. Thanks for your help.
This is what I have so far:
<?php
function povprecje($d,$t){
$v=0;
foreach($t as $x=>$y){
foreach($y as $d=>$grade){
$v = $v+$grade;
$v = $v/count($grade);
return $v;
}
}
}
$t = array(
"Student" => array(
"math" => 3,
"algebra" => 4,
"science" => 4
)
);
echo povprecje("math",$t);
?>

Maybe You wanted to achieve this?
function povprecje($sSubject, $aGrades) {
$iGradesSum = 0;
$iAmount = 0;
foreach($aGrades as $aStudentGrades) {
if(isset($aStudentGrades[$sSubject])) {
$iGradesSum+= $aStudentGrades[$sSubject];
$iAmount++;
}
}
return $iGradesSum / $iAmount;
}
Function call:
echo povprecje("math", $t);

Related

How to get the sum of salaries from a multidimentional array after condition

In this project i have a multidimentional array that keeps some employees names, their position, their speciality and their salary. I need to find the average salary of all the managers and all the employees from the array.
<!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>
I need to calculate the average salaries of employees and managers separately. So i thought of putting a condition in the Foreach() to check who is who and then count them and keep the sum of their salary. But it doesn't work properly. I would appreciate some help.
Basically:
To calculate the average sum up all different figures and then divide them through the total amount of figures.
So this part should be right.
Can you please check the datatypes of each from them:
$hmean = $sumsalary_e / $cEmployees;
$gmean = $sumsalary_m / $cManagers;
Every type should be an Integer or Int.
You only need one loop not 2 in this case, then all the occurances you want to check or dd up are members of the inner arrays
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;
}
this will proccess any occuption and calculate avarage salary. You can add an IF statment if you only need managers and Employee. You can leave it as be if at a later state other occuptions are added.
$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"),
);
function averageCount($employees)
{
$count = [];
foreach ($employees as $employee) {
$occupation = $employee['occupation'];
if (!array_key_exists($occupation, $count)) {
$count[$occupation]['occupation'] = $occupation;
$count[$occupation]['salary'] = $employee['salary'];
$count[$occupation]['count'] = 1;
} else {
$count[$occupation]['salary'] += $employee['salary'];
$count[$occupation]['count']++;
}
}
if (count($count) > 0) {
foreach ($count as $occupation => $item) {
$count[$occupation]['average'] = $item['salary'] / $item['count'];
}
}
return $count;
}
var_dump(averageCount($employees));

how to break function array in rows?

I have this php function in codeigniter where it fetches the data from my database:
function fetch_data()
{
$data = $this->projectionchart_model->make_query();
$array = array();
foreach($data as $row)
{
$array[] = $row;
}
$output = array(
'current' => intval($_POST["current"]),
'rowCount' => 10,
'total' => intval($this->projectionchart_model->count_all_data()),
'rows' => $array
);
echo json_encode($output);
}
I want to use the number_format function to some of columns and right now it's building everything in an array. How could I remove the array and list the data individually as variables so I can apply a function to some of them and then output them?
Thank you
Edit: explaining in more detail
This function fetch_data() calls the make_query() function stored in the projectionchart_model file which contains the following:
function make_query()
{
if(isset($_POST["rowCount"]))
{
$this->records_per_page = $_POST["rowCount"];
}
else
{
$this->records_per_page = 10;
}
if(isset($_POST["current"]))
{
$this->current_page_number = $_POST["current"];
}
$this->start_from = ($this->current_page_number - 1) * $this->records_per_page;
$this->db->select("*");
$this->db->from("projection_chart");
if(!empty($_POST["searchPhrase"]))
{
$this->db->like('ae', $_POST["searchPhrase"]);
$this->db->or_like('client', $_POST["searchPhrase"]);
$this->db->or_like('product', $_POST["searchPhrase"]);
$this->db->or_like('week_of', $_POST["searchPhrase"]);
$this->db->or_like('month', $_POST["searchPhrase"]);
$this->db->or_like('type', $_POST["searchPhrase"]);
}
if(isset($_POST["sort"]) && is_array($_POST["sort"]))
{
foreach($_POST["sort"] as $key => $value)
{
$this->db->order_by($key, $value);
}
}
else
{
$this->db->order_by('id', 'DESC');
}
if($this->records_per_page != -1)
{
$this->db->limit($this->records_per_page, $this->start_from);
}
$query = $this->db->get();
return $query->result_array();
}
So the output currently is this:
I want to format the Planned Spend, Cleared and Total Commission with the number_format php function but right now it's all in an array.
How could I accomplish this?

How to format json to what I need?

ok, Going to get this out of the way right now. I suck at php. I am building an angular app that is going to populate a mobile app with data from the database. I having it pull from the database just fine but I need the json formatted in a special way and I have no idea how to do it.
Using json_encode this is how it is coming from the database:
[
{
"id":"1",
"date":"2014-10-03",
"time":"2014-10-03 10:45:05",
"amount":"5"
},
{
"id":"2",
"date":"2014-10-03",
"time":"2014-10-03 12:21:05",
"amount":"2"
}
]
This is how I need it organized (this is just dummy data im using in on the angular side)
[
{
date: '2014-09-04',
feeding: [
{
id: '1',
time: '1409852728000',
amount: '3'
},
{
id: '2',
time: '1409874328000',
amount: '4'
},
]
},
{
date: '2014-09-05',
feeding: [
{
id: '3',
time: '1409915908000',
amount: '3.5'
},
{
id: '4',
time: '1409957908000',
amount: '5'
},
]
},
]
I needs to be seperated out and grouped by date. How would I go about doing this?
Airtech was just about there. Small update to the function though. The feeding value needs to be an array of objects rather than an object. You then need to push individual objects into that array.
function dateparse($in) {
$in = json_decode($in);
$out = array();
for ($i = 0; $i < sizeof($in); $i++) {
$date = $in[$i]->date;
$isFound = false;
for ($i2 = 0; $i2 < sizeof($out); $i2++) {
if ($date == $out[$i2]["date"]) {
// We've already run into this search value before
// So add the the elements
$isFound = true;
$out[$i2]["feeding"][] = array(
"id" => $in[$i]->id,
"time" => $in[$i]->time,
"amount" => $in[$i]->amount);
break;
}
}
if (!$isFound) {
// No matches yet
// We need to add this one to the array
$feeding = array("id" => $in[$i]->id, "time" => $in[$i]->time, "amount" => $in[$i]->amount);
$out[] = array("date" => $in[$i]->date, "feeding" => array($feeding));
}
}
return json_encode($out);
}
How about the following? I tested it on your json input example and it ran fine.
function parse($in)
{
$in = json_decode($in);
$out = array();
for ($i = 0; $i < sizeof($in); $i++) {
$date = $in[$i]->date;
$isFound = false;
for ($i2 = 0; $i2 < sizeof($out); $i2++) {
if ($date == $out[$i2]["date"]) {
// We've already run into this search value before
// So add the the elements
$isFound = true;
$out[$i2][]["feeding"] = array(
"id" => $in[$i]->id,
"time" => $in[$i]->time,
"amount" => $in[$i]->amount);
break;
}
}
if (!$isFound) {
// No matches yet
// We need to add this one to the array
$out[] = array("date" => $in[$i]->date, "feeding" => array(
"id" => $in[$i]->id,
"time" => $in[$i]->time,
"amount" => $in[$i]->amount));
}
}
return json_encode($out);
}
How about this ? This works fine and works as expected :) :-
function dateparse($var)
{
$counter=0; $var = json_decode($var); $date=array();
foreach($var as $key=>$value){foreach($value as $val1=>$val2)
{if($val1 == "date")
{foreach($value as $val3=>$val4)
{if($val3!="date") //because we don't want date again
{
$date[$val2]["feeding"][$counter][$val3] = $val4; continue;
}}continue;
}
}$counter++;}
return json_encode($date);}

PHP equivalent of Excel vlookup on array

After looking for a built in function in php I couldn't find a similar function to Excel's vlookup function.
I need a function that takes in an array and a lookup value and return the required info. So for example:
<?php
$baseCalculationPrice = [
0 => 50, //for values <=500 but >0
500 => 18, //for values <=3000 but >500
3000 => 15, //for values <=5000 but >3000
5000 => 14, //for values >5000
];
//Examples
$numPages = 499;
echo vlookup($numPages,$baseCalculationPrice); //should output 50
$numPages = 500;
echo vlookup($numPages,$baseCalculationPrice); //should output 50
$numPages = 501;
echo vlookup($numPages,$baseCalculationPrice); //should output 18
$numPages = 3000;
echo vlookup($numPages,$baseCalculationPrice); //should output 18
$numPages = 3001;
echo vlookup($numPages,$baseCalculationPrice); //should output 15
$numPages = 5000;
echo vlookup($numPages,$baseCalculationPrice); //should output 15
$numPages = 5001;
echo vlookup($numPages,$baseCalculationPrice); //should output 14
function vlookup($value,$array){
//magic code
return ....;
}
?>
I'm stuck even with the logic behind such a function, so any help would be great - thanks.
function vlookup($lookupValue,$array){
$result;
//test each set against the $lookupValue variable,
//and set/reset the $result value
foreach($array as $key => $value)
{
if($lookupValue > $key)
{
$result = $value;
}
}
return $result;
}
function testDeductionRate(){echo $this->deductionRate('ks',300);//zone and time are parameter for deductionRate() }
//deduction will be acted as vlookup (rangeLookup true)
function deductionRate($zone,$time){
$actualRate = 0;
$allRate = array(
'tg'=>array(0=>0,20=>200,30=>300,40=>400,50=>500),
'ks'=>array(0=>0,20=>100,30=>200,40=>300,50=>400),
'pc'=>array(0=>0,20=>50,30=>100,40=>200,50=>300)
);
if(isset($allRate[$zone])){
$rate = $allRate[$zone];
foreach($rate as $key=>$val){
if($time>=$key) $actualRate = $val;
}
}else{
return -1; //-1 means error
}
return $actualRate;
}
Try this if you would like to query on multi dimension associative array:
function vlookup($lookup_vakue, $lookup_array, $lookup_column, $result_column)
{
foreach ($lookup_array as $item) {
if ($item[$lookup_column] == $lookup_vakue) {
return $item[$result_column];
}
}
return false;
}
Sample Data
$data =
[
['id'=>1,'price'=>100],
['id'=>2,'price'=>200],
['id'=>3,'price'=>300]
];
Query Option
$result = vlookup('2',$data, 'id','price');
Result:
200
$getbase= function($amount) use ($baseCalculationPrice)
{
return (end(array_filter(
$baseCalculationPrice,function ($key) use ($amount)
{
return $key < $amount;
},
ARRAY_FILTER_USE_KEY
)));
};
amount 150 result 50
amount 1500 result 18
amount 25000 result 14

Looping class, for template engine kind of thing

I am updating my class Nesty so it's infinite but I'm having a little trouble.... Here is the class:
<?php
Class Nesty
{
// Class Variables
private $text;
private $data = array();
private $loops = 0;
private $maxLoops = 0;
public function __construct($text,$data = array(),$maxLoops = 5)
{
// Set the class vars
$this->text = $text;
$this->data = $data;
$this->maxLoops = $maxLoops;
}
// Loop function
private function loopThrough($data)
{
if( ($this->loops +1) > $this->maxLoops )
{
die("ERROR: Too many loops!");
}
else
{
$keys = array_keys($data);
for($x = 0; $x < count($keys); $x++)
{
if(is_array($data[$keys[$x]]))
{
$this->loopThrough($data[$keys[$x]]);
}
else
{
return $data[$keys[$x]];
}
}
}
}
// Templater method
public function template()
{
echo $this->loopThrough($this->data);
}
}
?>
Here is the code you would use to create an instance of the class:
<?php
// The nested array
$data = array(
"person" => array(
"name" => "Tom Arnfeld",
"age" => 15
),
"product" => array (
"name" => "Cakes",
"price" => array (
"single" => 59,
"double" => 99
)
),
"other" => "string"
);
// Retreive the template text
$file = "TestData.tpl";
$fp = fopen($file,"r");
$text = fread($fp,filesize($file));
// Create the Nesty object
require_once('Nesty.php');
$nesty = new Nesty($text,$data);
// Save the newly templated text to a variable $message
$message = $nesty->template();
// Print out $message on the page
echo("<pre>".$message."</pre>");
?>
Here is a sample template file:
Dear <!--[person][name]-->,
Thanks for contacting us regarding our <!--[product][name]-->. We will try and get back to you within the next 24 hours.
Please could you reply to this email to certify you will be charged $<!--[product][price][single]--> for the product.
Thanks,
Company.
The problem is that I only seem to get "string" out on the page... :(
Any ideas?
if(is_array($data[$keys[$x]]))
{
$this->loopThrough($data[$keys[$x]]);
}
else
{
return $data[$keys[$x]];
}
You need to return from the first if statement.
if(is_array($data[$keys[$x]]))
{
return $this->loopThrough($data[$keys[$x]]);
}
else
{
return $data[$keys[$x]];
}
This will get you a result back when you recurse. You're only getting "string" back right now because that key is only 1 level deep in your array structure.

Categories