I have MySQL with Float Values which are pressure parametters. I need to calculate average. But the code I make returns me average "empty" in my json response.
Here is the json response I get:
{"result":{"pressure":{"min":[{"Id":"2","presion":"0","Insertado":"2016-08-16 16:20:08"},{"Id":"5","presion":"0","Insertado":"2016-08-16 18:09:04"}],"max":[{"Id":"3","presion":"55","Insertado":"2016-08-16 16:22:14"}],"avg":[]},"last_entry":{"Id":"8","presion":"50","Insertado":"2016-08-16 18:28:45"}}}
As it shows. avg give empty!.
This is code in PHP
$press_values = get_press_values($json_object->result);
// get pressure result set with respected values
$press_result = get_press_result_set_from_values($json_object->result,$press_values);
// get latest entry
$latest_entry = get_latest_date_entry($json_object->result);
// Wrap results in an array
$output_result = array(
'pressure' => $press_result,
'last_entry' => $latest_entry
);
}
Then.
function get_press_values($result){
$min = -1;
$max = -1;
$avg = -1;
// get all pressure values
$pressures = array_map(function($result_item) {
return intval($result_item->presion);
}, $result);
if($pressures){
$min = min($pressures);
$max = max($pressures);
$avg = intval(calculate_average($pressures));
}
return array(
'min' => $min,
'max' => $max,
'avg' => $avg
);
}
Then:
function get_press_result_set_from_values($array,$value){
$min_objs = array();
$max_objs = array();
$avg_objs = array();
foreach ($array as $item) {
if($item->presion == $value['min']){
$min_objs[] = $item;
}
if($item->presion == $value['max']){
$max_objs[] = $item;
}
if($item->presion == $value['avg']){
$avg_objs[] = $item;
}
}
return array(
'min' => $min_objs,
'max' => $max_objs,
'avg' => $avg_objs,
);
}
then:
function calculate_average($arr) {
$total = 0;
$count = count($arr); //total numbers in array
foreach ($arr as $value) {
$total = $total + $value; // total value of array numbers
}
$average = ($total/$count); // get average value
return $average;
}
This part in your code:
if($item->presion == $value['avg']){
$avg_objs[] = $item;
}
will only add an item if the presion perfectly matches the average, which can be very unlikely, depending on your data of course.
update: For example you have the values 50, 51, 54, 55. The average is 53. Your code will not find any $item->presion which is equal to 53, because the average doesn't need an item that has that value (in contrast to min and max).
You should check if you actually mean the median (which has to be determined in a different way ...).
update2: to get the average into your result, you have to change
$avg_objs = array(); to $avg_objs = $value['avg'];. and remove the part from your code that I posted above.
Also, if you want your average to not be an integer, you should change the line
$average = ($total/$count);
to
$average = (float)$total / $count;
and remove the intval from:
$avg = intval(calculate_average($pressures));
Related
I have a phone book array I get from a database, where everyone appears once with their stationary phone number and a second with their mobile number.
I need to make this an array where everyone has only one line, with their phone number and mobile number
//My array
$data = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234'),
array('name'=>'robert','family'=>'bridgstone','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244'),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778'),
array('name'=>'ben','family'=>'wais','phone'=>'04472861558878'),
);
//The result that should come out
$data = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244','phone'=>''),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778','phone'=>'04472861558878')
);
I would do it the following way:
first I would generate a unique key that identify the row (in your case the name and the family, for example).
then check if a element with the same key exist, if it already exist merge the two component.
Optional if you only want an array of values transform the result with array_value function.
$dataArray = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234'),
array('name'=>'robert','family'=>'bridgstone','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244'),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778'),
array('name'=>'ben','family'=>'wais','phone'=>'04472861558878'),
);
$result = [];
foreach($dataArray as $data){
//Just in case that the name or the family is not assigned (operator ??)
$key = ($data['name']??'').'-'.($data['family']??'');
$result[$key] = array_merge($result[$key]??[],$data);
}
//Optional, get only the array values
$result = array_values($result);
I did so
$data = array(
array('name'=>'robert','family'=>'bridgstone','home'=>'0258101234'),
array('name'=>'robert','family'=>'bridgstone','phone'=>'07258101235'),
array('name'=>'dan','family'=>'swartz','home'=>'098101244'),
array('name'=>'ben','family'=>'wais','home'=>'0447256155778'),
array('name'=>'ben','family'=>'wais','phone'=>'04472861558878'),
);
count($data) < 2 ? exit(): $data;
for($i=0;$i<count($data);$i++){
$array_unique[$i] = $data[$i]["name"];
$array_unique[$i] = $data[$i]["family"];
}
$array_unique = array_unique($array_unique);
if(count($array_unique) == 1){
$last_array[0]=$array_unique[0];
$last_array[0]["phone"]=$array_unique[0]["phone"];
}
else{
$array_uniqueKeys = array_keys($array_unique);
for($i = 0;$i < count($array_unique);$i++){
$firstIndex = $i + 1;
$firstIndex == count($array_unique) ? $nextKey = count($data) : $nextKey = $array_uniqueKeys[$firstIndex];
$paar = $nextKey - $array_uniqueKeys[$i];
$dataslice = array();
$i3=0;
for($i2 = $array_uniqueKeys[$i];$i2 < ($array_uniqueKeys[$i]+$paar);$i2++){
if(in_array($i2,$array_uniqueKeys)){
$last_array[$i]=$data[$i2];
}
else{
$last_array[$i]["phone"]=$data[$i2]["phone"];
}
$i3++;
}
}
}
print_r($last_array);
I have an array;
$arr=array(1100,3150,4430,4430,5170,7450,7450,7450,8230);
I want to show them in graph. I want my Y-Axis as my elements of that array and X-Axis as sum up the numbers until that element. (x1,x1+x2,x1+x2+x3,...)
My graph will be;
Y-Axis : 1100,3150,4430,4430,5170,7450,7450,7450,8230
X-Axis : 1100,4250,8680,13110,18280,25730,33180,40630,48860
But I have no idea about how to do that. Is there anyone who can help me with it ? Thanks.
My entire code:
<?php
echo " ".'<br>'.'<br>';
$arr=array(1100,3150,4430,4430,5170,7450,7450,7450,8230);
$arrtotal=0;
for($i=0; $i<=8; $i++)
{
if ($arr[$i]<100) {
$arr[$i]=$arr[$i];
}
else
{
$arr[$i]=$arr[$i]/1000;
$arr[$i]=(string)$arr[$i];
}
}
function calculate($arr, $output){
switch($output){
case 'mean':
$count = count($arr)+1;
$sum = array_sum($arr);
$total = $sum / $count;
break;
case 'median':
rsort($arr);
$middle = (count($arr) / 2)+1;
$total = $arr[$middle-1];
break;
case 'mode':
$v = array_count_values($arr);
arsort($v);
foreach($v as $k => $v){$total = $k; break;}
break;
}
return $total;
}
function sd_square($x, $total) { return pow($x - $total,2); }
function sd($arr) {
return sqrt(array_sum(array_map("sd_square", $arr, array_fill(0,count($arr), (array_sum($arr) / count($arr)) ) ) ) / (count($arr)-1) );
}
echo ' '.'<br>';
echo "Values: ";
echo json_encode($arr).'<br>';
echo 'Mean: '.calculate($arr, 'mean').'<br>';
echo 'Median: '.calculate($arr, 'median').'<br>';
echo 'Mode: '.calculate($arr, 'mode').'<br>';
echo "Standart Derivation: ".sd($arr);
?>
<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function () {
var data = <?php echo json_encode($arr, JSON_NUMERIC_CHECK); ?>;
data = data.map(function (row, index) {
return {
x: index,
y: row
};
});
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Analysis"
},
axisY: {
title: "Variables"
},
data: [{
type: "line",
dataPoints: data
}]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 250px; width: 50%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
In this code my X-Axis is (0,1,2,3,4,5,6,7,8) and I don't want that.
I'm sorry if I couldn't explain well, English is not my native language.
The simplest way is just to loop over the values, adding the current array value to the previous output value to create the new output value. You can then convert that into an array of [x => y] values using array_combine:
$arr=array(1100,3150,4430,4430,5170,7450,7450,7450,8230);
$out = array($arr[0]);
for ($i = 1; $i < count($arr); $i++) {
$out[$i] = $out[$i-1] + $arr[$i];
}
$arr = array_combine($out, $arr);
print_r($arr);
Output:
Array (
[1100] => 1100
[4250] => 3150
[8680] => 4430
[13110] => 4430
[18280] => 5170
[25730] => 7450
[33180] => 7450
[40630] => 7450
[48860] => 8230
)
Demo on 3v4l.org
to get that one array into 2 arrays of graph co-ordinates, you can do this:
$x = array();
$y = array();
$running_total = 0;
for($i = 0; $i < count($arr); $i++){
$y[$i] = $arr[$i];
$running_total += $arr[$i];
$x[$i] = $running_total;
}
This will give you two arrays; array $x that contains a list of your X-coordinates, and $y, that gives you a list of your Y-coordinates; and you will still have access to your original $arr array, should you need to do further calculations on it. Based on your question, I think that will get you what you need.
However, if you are saying you want 1 array where the X co-ordinates are the array indexes, and the value is the array value itself, for example $y[3150] = 4250, then that is impossible; because you have duplicates in your original list, you cannot use those values as array indexes without ending up overwriting them.
(At least, not without making each array value an array itself, but that is taking things an order of magnitude above where is probably necessary)
Calculating the running total and storing the data as key-value pairs can be achieved with a foreach() and zero function calls.
Although perhaps a little unorthodox, it is valid syntax to use the "addition assignment" operator as the key of the output array. This updates the $previous value and supplies the calculated value as the key.
Code: (Demo)
$arr = [1100,3150,4430,4430,5170,7450,7450,7450,8230];
$result = [];
$previous = 0;
foreach ($arr as $value) {
$result[$previous += $value] = $value;
}
var_export($result);
// same result as #Nick's answer
I use CodeIgniter, and when an insert_batch does not fully work (number of items inserted different from the number of items given), I have to do the inserts again, using insert ignore to maximize the number that goes through the process without having errors for existing ones.
When I use this method, the kind of data I'm inserting does not need strict compliance between the number of items given, and the number put in the database. Maximize is the way.
What would be the correct way of a) using insert_batch as much as possible b) when it fails, using a workaround, while minimizing the number of unnecessary requests?
Thanks
The Correct way of inserting data using insert_batch is :
CI_Controller :
public function add_monthly_record()
{
$date = $this->input->post('date');
$due_date = $this->input->post('due_date');
$billing_date = $this->input->post('billing_date');
$total_area = $this->input->post('total_area');
$comp_id = $this->input->post('comp_id');
$unit_id = $this->input->post('unit_id');
$percent = $this->input->post('percent');
$unit_consumed = $this->input->post('unit_consumed');
$per_unit = $this->input->post('per_unit');
$actual_amount = $this->input->post('actual_amount');
$subsidies_from_itb = $this->input->post('subsidies_from_itb');
$subsidies = $this->input->post('subsidies');
$data = array();
foreach ($unit_id as $id => $name) {
$data[] = array(
'date' => $date,
'comp_id' => $comp_id,
'due_date' => $due_date,
'billing_date' => $billing_date,
'total_area' => $total_area,
'unit_id' => $unit_id[$id],
'percent' =>$percent[$id],
'unit_consumed' => $unit_consumed[$id],
'per_unit' => $per_unit[$id],
'actual_amount' => $actual_amount[$id],
'subsidies_from_itb' => $subsidies_from_itb[$id],
'subsidies' => $subsidies[$id],
);
};
$result = $this->Companies_records->add_monthly_record($data);
//return from model
$total_affected_rows = $result[1];
$first_insert_id = $result[0];
//using last id
if ($total_affected_rows) {
$count = $total_affected_rows - 1;
for ($x = 0; $x <= $count; $x++) {
$id = $first_insert_id + $x;
$invoice = 'EBR' . date('m') . '/' . date('y') . '/' . str_pad($id, 6, '0', STR_PAD_LEFT);
$field = array(
'invoice_no' => $invoice,
);
$this->Companies_records->add_monthly_record_update($field,$id);
}
}
echo json_encode($result);
}
CI_Model :
public function add_monthly_record($data)
{
$this->db->insert_batch('monthly_record', $data);
$first_insert_id = $this->db->insert_id();
$total_affected_rows = $this->db->affected_rows();
return [$first_insert_id, $total_affected_rows];
}
AS #q81 mentioned, you would split the batches (as you see fit or depending on system resources) like this:
$insert_batch = array();
$maximum_items = 100;
$i = 1;
while ($condition == true) {
// code to add data into $insert_batch
// ...
// insert the batch every n items
if ($i == $maximum_items) {
$this->db->insert_batch('table', $insert_batch); // insert the batch
$insert_batch = array(); // empty batch array
$i = 0;
}
$i++;
}
// the last $insert_batch
if ($insert_batch) {
$this->db->insert_batch('table', $insert_batch);
}
Edit:
while insert batch already splits the batches, the reason why you have "number of items inserted different from the number of items given" might be because the allowed memory size is reached. this happened to me too many times.
I am getting 2 arrays from the database, in both of the arrays there is a capital_payment which is 80 in both of them. So what I am trying to accomplish is that, the user gives a input which I get from $amount, of 90 , then I only select the row which has less than 90 , if the user selects 160 or 160+ i return both the rows, if the user selects 159 I return only one row . So that is basically the criteria I need to work with. I am trying to return the data in a array depending on the criteria. But I am making to many mistakes so need help.
public function GetSellLoanData($token, $amount, $expirationDate, $radioChecked, $orig_id)
{
$result = $this->investment->getLoansBorrowedData($id, $orig_id);
$foo = json_decode(json_encode($result), true);
$amountTemp = 0;
$data = array();
foreach($foo as $investment)
{
//check if input Amount greater than $AmountTemp from for each loop
if($amount > $amountTemp)
{
$data[] = $investment;
//DO a check to see what happens to the array data
foreach($data[] as $check){
}
// see if the new array did not exceed the $amount
//adding rows here
$data[] = $investment;
}else{
break;
}
$amountTemp += $investment['capital_payment'];
}
return $data;
}
}
And also I want to return all the other information in the array selected so I guess my $data array is not right as well.
Made some new changes! Hope this works!
$amountTemp = 0;
$data = array();
foreach($foo as $investment)
{
//check if input Amount greater than $AmountTemp from for each loop
if($amount > $amountTemp + $investment['capital_payment'])
{
$data[] = $investment;
}else{
break;
}
$amountTemp += $investment['capital_payment'];
}
I have an array of my inventory (ITEMS A & B)
Items A & B are sold as sets of 1 x A & 2 x B.
The items also have various properties which don't affect how they are distributed into sets.
For example:
$inventory=array(
array("A","PINK"),
array("A","MAUVE"),
array("A","ORANGE"),
array("A","GREY"),
array("B","RED"),
array("B","BLUE"),
array("B","YELLOW"),
array("B","GREEN"),
array("B","BLACK")
);
I want to redistribute the array $inventory to create $set(s) such that
$set[0] => Array
(
[0] => array(A,PINK)
[1] => array(B,RED)
[2] => array(B,BLUE)
)
$set[1] => Array
(
[0] => array(A,MAUVE)
[1] => array(B,YELLOW)
[2] => array(B,GREEN)
)
$set[2] => Array
(
[0] => array(A,ORANGE)
[1] => array(B,BLACK)
[2] => NULL
)
$set[3] => Array
(
[0] => array(A,GREY)
[1] => NULL
[2] => NULL
)
As you can see. The items are redistributed in the order in which they appear in the inventory to create a set of 1 x A & 2 x B. The colour doesn't matter when creating the set. But I need to be able to find out what colour went into which set after the $set array is created. Sets are created until all inventory is exhausted. Where an inventory item doesn't exist to go into a set, a NULL value is inserted.
Thanks in advance!
I've assumed that all A's come before all B's:
$inventory=array(
array("A","PINK"),
array("A","MAUVE"),
array("A","ORANGE"),
array("A","GREY"),
array("B","RED"),
array("B","BLUE"),
array("B","YELLOW"),
array("B","GREEN"),
array("B","BLACK")
);
for($b_start_index = 0;$b_start_index<count($inventory);$b_start_index++) {
if($inventory[$b_start_index][0] == 'B') {
break;
}
}
$set = array();
for($i=0,$j=$b_start_index;$i!=$b_start_index;$i++,$j+=2) {
isset($inventory[$j])?$temp1=$inventory[$j]:$temp1 = null;
isset($inventory[$j+1])?$temp2=$inventory[$j+1]:$temp2 = null;
$set[] = array( $inventory[$i], $temp1, $temp2);
}
To make it easier to use your array, you should make it something like this
$inv['A'] = array(
'PINK',
'MAUVE',
'ORANGE',
'GREY'
);
$inv['B'] = array(
'RED',
'BLUE',
'YELLOW',
'GREEN',
'BLACK'
);
This way you can loop through them separately.
$createdSets = $setsRecord = $bTemp = array();
$bMarker = 1;
$aIndex = $bIndex = 0;
foreach($inv['A'] as $singles){
$bTemp[] = $singles;
$setsRecord[$singles][] = $aIndex;
for($i=$bIndex; $i < ($bMarker*2); ++$i) {
//echo $bIndex.' - '.($bMarker*2).'<br/>';
if(empty($inv['B'][$i])) {
$bTemp[] = 'null';
} else {
$bTemp[] = $inv['B'][$i];
$setsRecord[$inv['B'][$i]][] = $aIndex;
}
}
$createdSets[] = $bTemp;
$bTemp = array();
++$bMarker;
++$aIndex;
$bIndex = $bIndex + 2;
}
echo '<pre>';
print_r($createdSets);
print_r($setsRecord);
echo '</pre>';
To turn your array into an associative array, something like this can be done
<?php
$inventory=array(
array("A","PINK"),
array("A","MAUVE"),
array("A","ORANGE"),
array("A","GREY"),
array("B","RED"),
array("B","BLUE"),
array("B","YELLOW"),
array("B","GREEN"),
array("B","BLACK")
);
$inv = array();
foreach($inventory as $item){
$inv[$item[0]][] = $item[1];
}
echo '<pre>';
print_r($inv);
echo '</pre>';
Maybe you can use this function, assuming that:
... $inventory is already sorted (all A come before B)
... $inventory is a numeric array staring at index zero
// $set is the collection to which the generated sets are appended
// $inventory is your inventory, see the assumptions above
// $aCount - the number of A elements in a set
// $bCount - the number of B elements in a set
function makeSets(array &$sets, array $inventory, $aCount, $bCount) {
// extract $aItems from $inventory and shorten $inventory by $aCount
$aItems = array_splice($inventory, 0, $aCount);
$bItems = array();
// iterate over $inventory until a B item is found
foreach($inventory as $index => $item) {
if($item[0] == 'B') {
// extract $bItems from $inventory and shorten $inventory by $bCount
// break out of foreach loop after that
$bItems = array_splice($inventory, $index, $bCount);
break;
}
}
// append $aItems and $bItems to $sets, padd this array with null if
// less then $aCount + $bCount added
$sets[] = array_pad(array_merge($aItems, $bItems), $aCount + $bCount, null);
// if there are still values left in $inventory, call 'makeSets' again
if(count($inventory) > 0) makeSets($sets, $inventory, $aCount, $bCount);
}
$sets = array();
makeSets($sets, $inventory, 1, 2);
print_r($sets);
Since you mentioned that you dont have that much experience with arrays, here are the links to the php documentation for the functions I used in the above code:
array_splice — Remove a portion of the array and replace it with something else
array_merge — Merge one or more arrays
array_pad — Pad array to the specified length with a value
This code sorts inventory without any assumption on inventory ordering. You can specify pattern (in $aPattern), and order is obeyed. It also fills lacking entries with given default value.
<?php
# config
$aInventory=array(
array("A","PINK"),
array("A","MAUVE"),
array("A","ORANGE"),
array("A","GREY"),
array("B","RED"),
array("B","BLUE"),
array("B","YELLOW"),
array("B","GREEN"),
array("B","BLACK"),
array("C","cRED"),
array("C","cBLUE"),
array("C","cYELLOW"),
array("C","cGREEN"),
array("C","cBLACK")
);
$aPattern = array('A','B','A','C');
$mDefault = null;
# preparation
$aCounter = array_count_values($aPattern);
$aCurrentCounter = $aCurrentIndex = array_fill_keys(array_unique($aPattern),0);
$aPositions = array();
$aFill = array();
foreach ($aPattern as $nPosition=>$sElement){
$aPositions[$sElement] = array_keys($aPattern, $sElement);
$aFill[$sElement] = array_fill_keys($aPositions[$sElement], $mDefault);
} // foreach
$nTotalLine = count ($aPattern);
$aResult = array();
# main loop
foreach ($aInventory as $aItem){
$sElement = $aItem[0];
$nNeed = $aCounter[$sElement];
$nHas = $aCurrentCounter[$sElement];
if ($nHas == $nNeed){
$aCurrentIndex[$sElement]++;
$aCurrentCounter[$sElement] = 1;
} else {
$aCurrentCounter[$sElement]++;
} // if
$nCurrentIndex = $aCurrentIndex[$sElement];
if (!isset($aResult[$nCurrentIndex])){
$aResult[$nCurrentIndex] = array();
} // if
$nCurrentPosition = $aPositions[$sElement][$aCurrentCounter[$sElement]-1];
$aResult[$nCurrentIndex][$nCurrentPosition] = $aItem;
} // foreach
foreach ($aResult as &$aLine){
if (count($aLine)<$nTotalLine){
foreach ($aPositions as $sElement=>$aElementPositions){
$nCurrentElements = count(array_keys($aLine,$sElement));
if ($aCounter[$sElement] != $nCurrentElements){
$aLine = $aLine + $aFill[$sElement];
} // if
} // foreach
} // if
ksort($aLine);
# add empty items here
} // foreach
# output
var_dump($aResult);
Generic solution that requires you to specify a pattern of the form
$pattern = array('A','B','B');
The output will be in
$result = array();
The code :
// Convert to associative array
$inv = array();
foreach($inventory as $item)
$inv[$item[0]][] = $item[1];
// Position counters : int -> int
$count = array_fill(0, count($pattern),0);
$out = 0; // Number of counters that are "out" == "too far"
// Progression
while($out < count($count))
{
$elem = array();
// Select and increment corresponding counter
foreach($pattern as $i => $pat)
{
$elem[] = $inv[ $pat ][ $count[$i]++ ];
if($count[$i] == count($inv[$pat]))
$out++;
}
$result[] = $elem;
}