using foreach and while loop together - php

I have an array year_values containing some values like
$year_values = array();
foreach($year_strings as $str) {
$year_values[] = explode(",", $str);
}
then I apply a query for extracting some values from database
$sql = "SELECT inventory.holdingcost as holdingcost,
inventory.ordercost as ordercost, inventory.unitprice as unitprice,
inventory.lead_time as lead_time, items.id as iid
FROM inventory, items
WHERE inventory.item_name = items.item_name";
mysql_error();
$result = mysql_query($sql);
foreach($year_values as $vals) {
while ($row = mysql_fetch_row($result)) {
$w = $row[2];
$e = $row[0];
$r = $row[1];
$tt = $row[3];
$eo = sqrt(2 * $vals[5] * $r / ($e * $w));
$eoq = round($eo, 1);
$ro = $vals[5] / 360;
$rop = round($ro * $tt);
$op = round($vals[5] / $eoq, 1);
$cc = round(89 / $op);
$h = round((($eoq * $e * $w) / 2), 2);
$o = round((($r * $vals[5]) / $eoq), 2);
$z = round($h + $o, 2);
}
}
When I use foreach above while loop it just takes first value of $year_values as $vals[5], I want to make computations inside while for every value of array $year_values.
How to correct it?
repetition is occurring in value1 i.e $val[5] currently:
Value1 Value 2 Value 3
199 202 0.25
199 205 0.25
199 210 0.25
199 230 0.25
1698 202 0.25
1698 205 0.25
1698 210 0.25
1698 230 0.25
instead i want the values to be displayed like
Value1 Value 2 Value 3
199 202 0.25
1698 205 0.25
15 210 0.25
971 230 0.25

I guess you just have to store all your data, so you could reuse it.
$result = mysql_query($sql);
$rows = array() ;
while ($row = mysql_fetch_row($result)){
$rows[] = $row ;
}
foreach($year_values as $vals) {
foreach($rows as $row){
$w = $row[2];
$e = $row[0];
$r = $row[1];
$tt = $row[3];
$eo = sqrt(2 * $vals[5] * $r / ($e * $w));
$eoq = round($eo, 1);
$ro = $vals[5] / 360;
$rop = round($ro * $tt);
$op = round($vals[5] / $eoq, 1);
$cc = round(89 / $op);
$h = round((($eoq * $e * $w) / 2), 2);
$o = round((($r * $vals[5]) / $eoq), 2);
$z = round($h + $o, 2);
}
}

Simply reverse the statements:
while ($row = mysql_fetch_row($result)) {
foreach($year_values as $vals) {
$w = $row[2];
$e = $row[0];
$r = $row[1];
$tt = $row[3];
$eo = sqrt(2 * $vals[5] * $r / ($e * $w));
$eoq = round($eo, 1);
$ro = $vals[5] / 360;
$rop = round($ro * $tt);
$op = round($vals[5] / $eoq, 1);
$cc = round(89 / $op);
$h = round((($eoq * $e * $w) / 2), 2);
$o = round((($r * $vals[5]) / $eoq), 2);
$z = round($h + $o, 2);
}
}

mysql_fetch_row will return false once the rows have been fetched all. To reuse it you should store them in a variable (like the response made by Jari) or you could switch the two cycles (see imulsion's answer)

Related

How can I get the distance between points in an array of coordinates starting from 0 in php?

I trust you are well?
In PHP I have an array of coordinates. I want the distances between each coordinate starting from 0, so the first coordinate should be 0, then the second coordinate should be the distance between the first and the second and then the third should be the distance between second and the third, here is my code:
Coordinates:
$coordinates = [];
$coordinates[0]["Long"] = "299908186";
$coordinates[0]["Lat"] = "-271033949";
$coordinates[1]["Long"] = "281339992";
$coordinates[1]["Lat"] = "-261733281";
$coordinates[2]["Long"] = "280158333";
$coordinates[2]["Lat"] = "-262013500";
Here is the loop I want to do it in:
$earth_radius = 6371000;
$number = -1;
$long_from = 0;
$lat_from = 0;
$long_to = 0;
$lat_to = 0;
$angle = 0;
foreach($data as $row)
{
$long_f_radius = deg2rad($long_from);
$lat_f_radius = deg2rad($lat_from);
$long_t_radius = deg2rad($long_to);
$lat_t_radius = deg2rad($lat_to);
$long_delta = $long_t_radius - $long_f_radius;
$lat_deta = $lat_t_radius - $lat_f_radius;
$angle = 2 * asin(sqrt(pow(sin($lat_deta / 2), 2) +
cos($lat_f_radius) * cos($lat_t_radius) * pow(sin($long_delta / 2), 2)));
}
print_r($angle)
What am I doing wrong?

Add parameters in result array

I'm using Code Igniter,I try to add $finalamount to the result_array.
$this->db->select('customer_id, customer_ref, i_points, group_points, created_on');
$run_q = $this->db->get('employees');
if($run_q->num_rows() > 0){
foreach ($run_q->result_array() as $get) {
$totalpoints = $get['i_points'] + $get['group_points'];
$percent = 17;
$amountbycustomer = $totalpoints * 26 * $percent;
$amountbypref = $this->final($get['customer_id'],$percent);
$finalamount = $amountbycustomer + $amountbypref;
$get['finalamount'] = $finalamount;
}
return $run_q->result_array();
}
But in my view, this error
<td class="employeeCustomer"><?=$get['customer_id']?></td>
<td class="employeeCustomerRef"><?=$get['customer_ref']?></td>
<td class="employeeAmount"><?=$get['finalamount']?></td>//line 65
Message: Undefined index: finalamount
Filename: employees/employeeslist.php
Line Number: 65
You are returning just the result array from the db and not actually adding the final amount to the individual rows. You have to do something like this:
public function stmt() {
$this->db->select('customer_id, customer_ref, i_points, group_points, created_on');
$run_q = $this->db->get('employees');
if ($run_q->num_rows() > 0) {
$rows = $run_q->result_array();
foreach ($rows as $k => $get) {
$totalpoints = $get['i_points'] + $get['group_points'];
$percent = 17;
$amountbycustomer = $totalpoints * 26 * $percent;
$amountbypref = $this->final($get['customer_id'], $percent);
$finalamount = $amountbycustomer + $amountbypref;
$rows[$k]['finalamount'] = $finalamount;
}
return $rows;
}
return false;
}
OR using pass by reference (notice: &get):
$rows = $run_q->result_array();
foreach ($run_q->result_array() as &$get) {
$totalpoints = $get['i_points'] + $get['group_points'];
$percent = 17;
$amountbycustomer = $totalpoints * 26 * $percent;
$amountbypref = $this->final($get['customer_id'], $percent);
$finalamount = $amountbycustomer + $amountbypref;
$get['finalamount'] = $finalamount;
}
return $rows;

Random multiplication table generator

im creating an multiplication table system in PHP.
The input tho this system is an table number and the amount of questions.
The table 1 is skipped so 2 to input table
At this point I just fill an array like this:
$nCount = $_POST['count'];
$nHighest = $_POST['table'];
$aSums = [];
$nCounter = 0;
while($nCount > 0){
$cSumString = rand(2, $nHighest) . "*" . rand(1, 10);
$aSums[$nCounter] = $cSumString
$nCount--;
$nCounter++;
}
I want to parse the questions in multiple ways:
3 * 5 = ... (normal)
... * 5 = 25 (first number to fill in)
8 * ... = 16 (second to fill in)
This needs to be randomised.
Example:
1 * 2 = ...
6 * ... = 12
... * 4 = 20
8 * 4 = ...
2 * ... = 6
The only thing I know that should be able to so this is a switch but I cant seem to get it to work propperly so if anyone can give me a push in the right direction i would appreciate it. Im not asking for instacode just some tips would be great.
$nCount = $_POST['count'];
$nHighest = $_POST['table'];
$aSums = [];
$leftOut = ['leftFactor', 'rightFactor', 'product'];
for ($i = 0; $i <= $nCount; $i++) {
$leftOutRand = rand(0, count($leftOut) - 1);
$factor = rand(1, $nHighest);
$product = rand(0, $nHighest) * $factor;
switch($leftOut[$leftOutRand]) {
case 'leftFactor':
$cSumString = '...' . ' * ' . $factor . ' = ' . $product;
break;
case 'rightFactor':
$cSumString = $factor . ' * ' . '...' . ' = ' . $product;
break;
case 'product':
$cSumString = rand(1, $nHighest) . ' * ' . rand(1, $nHighest) . ' = ' . '...';
break;
}
$aSums[$i] = $cSumString;
}
example Output:
2 * ... = 4
... * 2 = 6
1 * 1 = ...
... * 2 = 6
3 * ... = 12
2 * ... = 2
2 * 4 = ...
4 * ... = 0
3 * 1 = ...
2 * 1 = ...
... * 4 = 16
1 * ... = 2
... * 2 = 2
1 * 4 = ...
3 * ... = 9
2 * 3 = ...
2 * ... = 6
... * 1 = 3
... * 4 = 4
1 * 1 = ...
... * 3 = 9
<?php
$total = 4;
$table = 7;
$generate_pair = function() use ($table)
{
$first = rand(1, 10);
$last = rand(2, $table);
return [$first, $last];
};
$pairs = [];
while (count($pairs) < $total) {
$pair = $generate_pair();
if(!in_array($pair, $pairs))
$pairs[] = $pair;
}
$questions = array_map(function ($v) {
return sprintf('%d * %d', $v[0], $v[1]);
}, $pairs);
var_dump($questions);
Example output:
array(4) {
[0]=>
string(5) "7 * 3"
[1]=>
string(5) "5 * 7"
[2]=>
string(5) "5 * 2"
[3]=>
string(5) "6 * 2"
}
I would personally put it in an array and read it from there then its easier to get it trough an switch like Mark labenski mentioned and I would do it like this:
$questpertable = floor($questions / ($table-1));
$nTableCounter = 2;
$array = [];
for ($nX = 0; $nX < ($table-1); $nX++){
for ($nY = 0; $nY < $questpertable;){
$left = rand(1, 10);
$right = $tablecounter;
$answer = $left * $right;
$array[$nY] = array($left, $right, $answer );
$Y++;
}
$tablecounter++;
}
The only thing that misses here is the residual value u will have to find something to fix this.

Welle's Wilder Accumulative Swing Index PHP calculation - Cannot return proper value

I am trying to get the accumulative swing index for an aapl stock chart. I am using this calculation for reference.
http://www.barchart.com/education/std_studies.php?what=int_swing&hideheader=true#study
This is what I have written so far. This should return 252.09 but I cannot get it to work.
$asi[0] = -78.75
$ht = 584; // High today
$lt = 574.25; // low
$ct = 584.00; // close
$ot = 578; // open
$hy = 574; // High yesterday
$ly = 565.61;
$cy = 569.05;
$oy = 571.67;
$k = max(($hy-$ct),($ly-$ct));
$abc = array(($ht-$cy), ($lt-$cy), ($ht-$lt));
$max = max($abc);
$r = 0;
if($max == $abc[0]){
$r = ($ht-$cy)-.5*($lt-$cy)+.25*($cy-$oy);
}elseif($max == $abc[1]){
$r = ($lt-$cy)-.5*($ht-$cy)+.25*($cy-$oy);
}elseif($max == $abc[2]){
$r = ($ht-$lt)+.25*($cy-$oy);
}else{
echo "Error in welles accumulative swing index";
exit;
}
$l = 3 //period;
$val = 50 * (($cy - $ct) + .5 *($cy - $oy) + .25*($ct-$ot)) / $r * $k / $l;
$asi[] = $asi[$i-1] + $val;
Any help would be greatly appreciated.
I have tried to implement this index newly symbol-by-symbol and have get different result (swing: -248.7032967033 ).
May be your control value wrong?
That is my code:
class Swing
{
public function calculate($high_price, $low_price, $close_price, $open_price, $t)
{
// (Ct-1 - Ct)
$summand0 = ($close_price[$t-1] - $close_price[$t]);
// 0.5(Ct-1 - Ot-1)
$summand1 = 0.5 * ($close_price[$t-1] - $open_price[$t-1]);
// 0.25(Ct - Ot)
$summand2 = 0.25 * ($close_price[$t] - $open_price[$t]);
$limit_move_default = 3.0;
$r = $this->get_r_value($high_price, $low_price, $close_price, $open_price, $t);
$k = $this->get_k_value($high_price, $low_price, $close_price, $t);
$factor0 = 50.0 * ($summand0 + $summand1 + $summand2) / $r;
$factor1 = $k / $limit_move_default;
// SWING = 50 * ((Ct-1 - Ct)+ 0.5(Ct-1 - Ot-1)+ 0.25(Ct - Ot))/ R * K / M
return $factor0 * $factor1;
}
public function get_k_value($high_price, $low_price, $close_price, $t)
{
// K= MAX(| Ht-Ct-1|, | Lt-Ct-1|)
return max(
abs($high_price[$t] - $close_price[$t-1]),
abs($low_price[$t] - $close_price[$t-1]));
}
public function get_r_value($high_price, $low_price, $close_price, $open_price, $t)
{
// A. |Ht-Ct-1|
$a = abs($high_price[$t] - $close_price[$t-1]);
// B. |Lt-Ct-1|
$b = abs($low_price[$t] - $close_price[$t-1]);
// C. |Ht-Lt|
$c = abs($high_price[$t] - $low_price[$t]);
$max_value = max($a, $b, $c);
$d = abs($high_price[$t] - $low_price[$t]);
if($a == $max_value)
// R= (| Ht-Ct-1|)-.5(| Lt-Ct-1|)+.25(| Ct-1-Ot-1|)
return $a - 0.5 * $b + 0.25 * $d;
if($b == $max_value)
// R= (| Lt-Ct-1|)-.5(| Ht-Ct-1|)+.25(| Ct-1-Ot-1|)
return $b - 0.5 * $a + 0.25 * $d;
if($c == $max_value)
// R= (| Ht-Lt|)+.25(| Ct-1-Ot-1|)
return $c + 0.25 * $d;
}
};
$swing = new Swing();
$high_price = array(574.0, 584.0);
$low_price = array(565.61, 574.25);
$close_price = array(569.05, 584.0);
$open_price = array(571.67, 578.0);
$value = $swing->calculate($high_price, $low_price, $close_price, $open_price, 1);
echo("swing: $value \n");
$d looks wrong.
It should be abs($close_price[$t-1] - $open_price[$t-1]);

SQL or PHP mistake? Distance calculation

I have a problem with my file. I'm making Travian Clone script and we went really far. Now we decided to add artefacts into game.
Goal is to show closest artefacts to the current village we are in. The code is:
function getDistance($coorx1, $coory1, $coorx2, $coory2) {
$max = 2 * WORLD_MAX + 1;
$x1 = intval($coorx1);
$y1 = intval($coory1);
$x2 = intval($coorx2);
$y2 = intval($coory2);
$distanceX = min(abs($x2 - $x1), $max - abs($x2 - $x1));
$distanceY = min(abs($y2 - $y1), $max - abs($y2 - $y1));
$dist = sqrt(pow($distanceX, 2) + pow($distanceY, 2));
return round($dist, 1);
}
unset($reqlvl);
unset($effect);
$arts = mysql_query("SELECT * FROM ".TB_PREFIX."artefacts WHERE id > 0");
$rows = array();
while($row = mysql_fetch_array($arts)) {
$query = mysql_query('SELECT * FROM `' . TB_PREFIX . 'wdata` WHERE `id` = ' . $row['vref']);
$coor2 = mysql_fetch_assoc($query);
$wref = $village->wid;
$coor = $database->getCoor($wref);
$dist = getDistance($coor['x'], $coor['y'], $coor2['x'], $coor2['y']);
$rows[$dist] = $row;
}
ksort($rows, SORT_ASC);
foreach($rows as $row) {
echo '<tr>';
echo '<td class="icon"><img class="artefact_icon_'.$row['type'].'" src="img/x.gif" alt="" title=""></td>';
echo '<td class="nam">';
echo ''.$row['name'].' <span class="bon">'.$row['effect'].'</span>';
echo '<div class="info">';
if($row['size'] == 1){
$reqlvl = 10;
$effect = "village";
}elseif($row['size'] == 2 OR $row['size'] == 3){
$reqlvl = 20;
$effect = "account";
}
echo '<div class="info">Treasury <b>'.$reqlvl.'</b>, Effect <b>'.$effect.'</b>';
echo '</div></td><td class="pla">'.$database->getUserField($row['owner'],"username",0).'</td>';
echo '<td class="dist">'.getDistance($coor['x'], $coor['y'], $coor2['x'], $coor2['y']).'</td>';
echo '</tr>';
}
?>
but the code seems to be wrong because its showing all same distances. 14.8 to me. I know i maybe have bad explanation but u will probably understand what I need.
I can't help with your current code I'm afraid but you could try using the Haversine Formula instead:
// Where:
// $l1 ==> latitude1
// $o1 ==> longitude1
// $l2 ==> latitude2
// $o2 ==> longitude2
function haversine ($l1, $o1, $l2, $o2) {
$l1 = deg2rad ($l1);
$sinl1 = sin ($l1);
$l2 = deg2rad ($l2);
$o1 = deg2rad ($o1);
$o2 = deg2rad ($o2);
$distance = (7926 - 26 * $sinl1) * asin (min (1, 0.707106781186548 * sqrt ((1 - (sin ($l2) * $sinl1) - cos ($l1) * cos ($l2) * cos ($o2 - $o1)))));
return round($distance, 2);
}
Credit goes to this post on go4expert.com, I've used this function in the past and found it works very well.

Categories