Calculation error with Numbers containing more than 3 Digits - php

I'm importing prices from a database using the following code:
//implode items, turn into string
$item_implode = join("','", $item_array);
//declare an overall array for result
$product = array();
$result = $mysqli->query("SELECT Name, WPrice as price, APrice as a_price from my_table where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode');");
while($row = $result->fetch_assoc()) {
$product_name = $row['Name'];
// find all keys in $item_array which value is the products
$keys = array_keys($item_array, $product_name);
foreach ($keys as $key) {
// add values for these keys
$product[$key + 1]["Name"] = $row['Name'];
$product[$key + 1]["price"] = number_format($row['price'],2);
$product[$key + 1]["a_price"] = number_format($row['a_price'],2);
}
}
And then I apply the following functions:
function price($m) {
global $product,$i;
if ($m == "a") {
$value = $product[$i]["a_price"];
}
else {
$value = $product[$i]["price"]; //
}
return $value;
}
I'm trying to use the following comparison:
<?php if ( price( a )< price( default ) ) {echo "Smaller";} ?>
To echo Smaller whenever the price of A is smaller than the default price.
It works fine for prices in the range of 0 to 999.99, but for when a price of 1,000 or more is involved, I'm getting the opposite results (it echos smaller when bigger and vice-versa)
What is causing this problem?

You're comparing strings because that's what you stored in $product["price"] and $product["a_price"] (the function number_format() returns a string value). For numbers >= 1000, those strings include commas, which breaks the comparison.
Compare the numeric values and don't call number_format() until you need to display the values.

Related

PHP Replace specific values inside formula

I have a formula where some of the data needs to be replaced by MYSQLI query results.
The formula can look like:
100+400-600-700
The numbers in the formula will match a specific table line in the DB and output correct value, for example:
121000+1000-8000-2000
I've tried to extract all the special characters from the original string in order to get the correct DB result via MYSQLI using formula:
preg_match_all('!\d+!', $rf, $matches);
foreach ($matches as $key1 => $value) {
//Declare summarization of TOT rows
$TOT = 0;
foreach ($value as $single) {
$querymatch = mysqli_query($mysqli, "SELECT rowMainAccount FROM reportTable_rowDefinitions WHERE rowCode = '$single' AND reportID = $rowDefinition");
$arraymatch = mysqli_fetch_array($querymatch);
$TOTaccount = $arraymatch['rowMainAccount'];
//Fetch values from FinancialTransactions
//Fetch values
$queryTOT = mysqli_query($mysqli, "SELECT SUM(debit) AS debitTOT, SUM(credit) AS creditTOT FROM FinancialTransactions WHERE mainAccount = $TOTaccount AND entity = $org AND date BETWEEN '$newStartDate' AND '$newEndDate'");
$arrayTOT = mysqli_fetch_array($queryTOT);
$TOTcred += $arrayTOT['creditTOT'];
$TOTdeb += $arrayTOT['debitTOT'];
}
$TOT += $TOTdeb - $TOTcred;
}
echo $TOT; //Returns values
This will only replace the numbers in the original string giving result as
121000100080002000
from foreach loop.
How can I put the returned values from DB into the original formula to acieve the correct output as
121000+1000-8000-2000
?
Use preg_replace_callback and in the callback you can get the appropriate value and return it to place it in the original string.

How to add the values from a foreach loop php

I have and foreach loop that outputs the totals I want to add when i echo the $val_tex it outputs in one number like "4911165" but if I echo it with a break tag it gives me the right values. It looks like
49
1
1
1
65
My question is how to get the sum of all the values which should equal "117"
$val_tex = array();
foreach ( $get_seller as $keys ) {
$val_tex = $keys['total'];
}
You have to add them together in the foreach loop - there's a simple way to do that $total += $keys['total']; It's just a simpler way of saying $total = $total + $keys['total'];
There are also other ways - $total = array_sum(array(1,2,3,4)); // == 10 for example. To get the sum from a single column, you get an array that only contains the values from the specific column first:
// an array of the values from that column
$arrayTotall = array_column($keys, 'total');
$total = array_sum($arrayTotals);
Your for each needs another variable to add them:
foreach ( $get_seller as $keys ) {
$val_tex = $keys['total'];
$sum = += $val_tex
//or...
$val_tex += $keys['total'];
//depending on how you want to us val_tex
}
The .= adds the value to previous value instead of overwriting it.

Removing data from MYSQL that is comma delimited via Get and php

What I am doing is adding values to a mysql table with each value seperated by a comma. And each new value is appended to that last value once again seperated by a comma. Now this is all dynamic. What I am having an issue is on how to remove a selected value and the comma. I am using php and mysql.
I can read the values out with explode and line[value].
table name is values
table consist of id, value, value_array
$value_selected would be a $_GET['value']
value_array is the column that contains all the values seperated by comma.
The database selects from values where the id is equal to the Get value.
Then returns all values in the value_array
I then explode the values and have each value from the value_array read through the for loop and line[value].
the code:
start php
$value_selected = $_GET['value'];
$query = mysql_query("SELECT * FROM values WHERE id='$value_selected'");
while($result = mysql_fetch_assoc($query))
{
$check_values = $result['value_array'];
}
$values = explode(",",$check_values);
$count_values = count($values);
for($counter = 0; $counter < $count_values; $counter++)
{
$line = each($values);
$query = mysql_query("SELECT * FROM values WHERE id='$line[value]'");
while($result = mysql_fetch_assoc($query))
{
echo $result['value'].'<br/>';
}
}
php end
I don't have an issue reading it out. What I'm trying to do is being able to select a value via GET and remove that value from the value_array while also removing the trailing comma. I hope I was able to expalin in more detail my issue.
Use a foreach loop, take the exploded string and reassemble it minus the string $value_selected by doing this:
$NewValue = '';
$i = 1;
foreach ($values as $Value) {
if ($i > $count_values) {
break;
} else {
if ($Value !== $value_selected) {//reassemble comma-sep string - $_GET['value']
$NewValue = $NewValue . $Value . ",";
}
}
$i++;
}
Now $NewValue no longer contains $_GET['value'], because the concatenation in the if statement only occurs when the exploded fragment $Value does not match $_GET['value']. Update the database or echo $NewValue, etc. as necessary at this point.

Json_encode - converting an array into a json object

I am currently fetching values from mysql table. The values are grabbed from a foreach loop. Then after the loop is done the array is converted into a json object. But I am having difficulties getting the json format in order to use with another api. My loop only display one result when there are two. Also I have a function that returns a hexadecimal value which is returning null when I call it inside the loop. How could I get those values in the format shown below?
header("Content-type: application/json");
//get the course list
$education_query = $db_con->prepare("SELECT a.type, COUNT(1) AS cnt
FROM academy a
GROUP BY a.type");
$education_query->execute();
$data = $education_query->fetchAll();
$output = array();
foreach ($data as $row) {
//$type = ;
$output["valueField"] = $row["type"];
$output["name"] = $row["type"];
$output["color"] = hexcode();
} // foreach ($data as $row) {
echo json_encode(array($output));
Current Result:
[{"valueField":"Upper-Secondary","name":"Upper-Secondary","color":null}]
Desired Result:
[{
valueField: "Post-Secondary",
name : "Post-Secondary",
color: "#40ae18"
},
{
valueField: "Upper-Secondary",
name : "Upper-Secondary",
color: "#aaab4b"
}]
EDIT(adding hexcode function):
function hexcode()
{
$min = hexdec("000000"); // result is 0 and sets the min-value for mt_rand
$max = hexdec("FFFFFF"); // result is 16777215 and sets the max-value for mt_rand
$random = mt_rand($min, $max); // creates a radom number between 0 and 16777215
$random_hex = dechex($random); // transforms the random number into a Hex-Code
// now the test, if the result has 6 chars
if (strlen($random_hex) != "6") // sometimes it returns an only 5, or less, char Hex-Code,
hexcode(); // so the function has to be repeat
else
echo $random_hex; // returns the Hex-Code
}
$output needs to be an array of arrays.
$addToOutput = array();
$addToOutput["valueField"] = $row["type"];
// add other fields
$output[] = $addToOutput;
your loop is displying one results because you're overwriting the array keys every time.
you can change those 3 lines
$output["valueField"] = $row["type"];
$output["name"] = $row["type"];
$output["color"] = hexcode();
to
$output[]["valueField"] = $row["type"];
$output[]["name"] = $row["type"];
$output[]["color"] = hexcode();
can you post the hexcode() function ?
EDIT
no need for all this code, you can use this :
function hexcode(){
return sprintf("#%02X%02X%02X", mt_rand(0, 255), mt_rand(0, 255), mt_rand(0,255));
}

How to do PHP matrix operation easily and gracefully?

I've a $max which is essentially a two dimensional array.
Each element in $max is eithor 1 or 0,
can be denoted by $max[$x][$y], where $x is an integer within 0~WIDTH,similar for $y
My purpose is to find rows and columns in the $maxthat sums up greater than a CONSTANT, and get the average distance between rows/columns that qualify.
Anyone has a good solution ?
I have not tested this, but it should work for summing up the columns and rows:
//Map columns and rows into their respective values
//Note that we preserve the col/row indexes
$rowval = array();
$colval = array();
foreach($max as $k1 => $row) {
$rowval[$k1] = array_sum($row);
foreach($row as $k2 => $col) {
if(!isset($colval[$k2])) {
$colval[$k2] = 0;
}
$colval[$k2] += $col;
}
}
//Define filter function
function is_over($val) {
return $val > CONSTANT;
}
//Filter out the cols/rows from their respective arrays
//Keys will be preserved by array_filter
$foundcols = array_filter($colval, 'is_over');
$foundrows = array_filter($rowval, 'is_over');
You still have to calculate the average distance though.

Categories