How to get max value in loop - php

ok so im working with this loop and getting information from DB:
for($i0 = 0; $i0 < $total0; $i0 ++) {
$id = $oconecta->retrieve_value($i0, "id_tam_product");
$price = $oconecta->retrieve_value($i0, "price_tam_product");
echo $id; // RESULTS: 312, 313, 314
echo $price; // RESULTS: 180.00, 250.00, 300.00
}
i was wondering how can i get the MAX value for that loop:
echo $id; //RESULTS: 314
echo $price; //RESULTS: 300.00

$maxID = 0;
$maxPrice = 0;
for($i0=0;$i0<$total0;$i0++)
{
$id=$oconecta->retrieve_value($i0,"id_tam_product");
$price=$oconecta->retrieve_value($i0,"price_tam_product");
$maxID = max($id, $maxID);
$maxPrice = max($price, $maxPrice);
}
echo "MAX ID: $maxID - Max PRICE: $maxPrice";
Use the max() function to determine the highest number of a set.

Either you use SQL's MAX() if you can modify your SQL query, or keep the max value in a variable in each loop, and reassign it everytime:
$firstLoop = true;
$maxId = 0;
$maxPrice = 0;
for ($i0 = 0; $i0 < $total0; $i0++)
{
$id = $oconecta->retrieve_value($i0, "id_tam_product");
$price = $oconecta->retrieve_value($i0, "price_tam_product");
if ($firstLoop) {
$firstLoop = false;
$maxId = $id;
$maxPrice = $price;
}
else {
$maxId = max($maxId, $id);
$maxPrice = max($maxPrice, $price);
}
}
(the boolean is here if you have negative values it wouldn't work if $maxPrice and $maxId are initiliazed with 0)

Related

How to access and return specific value of a foreach in PHP

So I have a request-response that looks like this
$json='[ {"item_cat":"Stationary","items":[{"item_name":"A4 Paper","qty":"2"},{"item_name":"Test Paper","qty":"6"}],"total":"2"},
{"item_cat":"Computer Accessory ","items":[{"item_name":"Power pack","qty":"2"}],"total":"1"},
{"item_cat":"Material","items":[{"item_name":"T-Shirt","qty":"3"},
{"item_name":"Cap","qty":"5"}],"total":"2"}]';
I'm trying to get each item_name and qty so I can use them to manipulate my db. Here is what I've done
$data = json_decode($json, true);
$len = count($data);
for($i =0; $i< $len; $i++){
$item_length = count($data[$i]['items']);
for($c=0; $c < $item_length; $c++){
foreach ($data[$i]['items'][$c] as $key => $value ) {
$qty = '';
if($key == "qty"){
$qty = $data[$i]['items'][$c];
}
if($key == 'item_name'){
$item_name = "$value";
}
$sql= $db->query("SELECT `stock` from `inventory` WHERE `item_name` = '$item_name'");
while ($sql1 = $sql->fetch_assoc()) {
$stock = $sql1['stock'];
}
if($stock > $qty ){
$stock_balance = $stock - $qty;
$quantity = (int)$qty;
$db->query("UPDATE `inventory` SET `stock` = (`stock` - '$quantity') WHERE `item_name` = '$item_name'");
}else{
echo "<h3> This Operation Not Allowed: Stock Balance Is Less Than The Request <h3>";
}
}
}
}
A non-numeric value encountered, which is as a result of $qty because I'm not able to return just qty value. I've tried several other means. I'm really exhausted. Would appreciate any help please. Cheers!
Let's decompose your code.
This is json:
[
{
"item_cat":"Stationary",
"items":[
{
"item_name":"A4 Paper",
"qty":"2"
},
{
"item_name":"Test Paper",
"qty":"6"
}
],
"total":"2"
},
{
"item_cat":"Computer Accessory ",
"items":[
{
"item_name":"Power pack",
"qty":"2"
}
],
"total":"1"
},
{
"item_cat":"Material",
"items":[
{
"item_name":"T-Shirt",
"qty":"3"
},
{
"item_name":"Cap",
"qty":"5"
}
],
"total":"2"
}
]
Now the array loop without the SQL (to ensure that it works as expected):
$data = json_decode($json, true);
$len = count($data);
for($i =0; $i< $len; $i++){
$item_length = count($data[$i]['items']);
for($c=0; $c < $item_length; $c++){
foreach ($data[$i]['items'][$c] as $key => $value ) {
$qty = '';
if($key == "qty"){
$qty = $data[$i]['items'][$c];
}
if($key == 'item_name'){
$item_name = "$value";
}
The problems here are: un-human variable names and not correct working with JSON object.
First of all, let us rename variables to something readable.
Example:
$data[$i] will be $catalog_entry (object)
$data[$i]['items'] will be $catalog_entry_items (array)
$data[$i]['items'][$c] will be $catalog_entry_item (one item, object)
Let's change the code with new variables:
$data = json_decode($json, true);
$len = count($data);
for($i =0; $i< $len; $i++) {
$catalog_entry = $data[$i];
$catalog_entry_items = $data[$i]['items'];
for($c=0; $c < sizeof($catalog_entry_items); $c++) {
$catalog_entry_item = $data[$i]['items'][$c];
$qty = $catalog_entry_item['qty'];
$item_name = $catalog_entry_item['item_name'];
echo $item_name . ' : ' . $qty . "\n"; // <-- this is for testing
}
}
Run this code and see the expected result:
A4 Paper : 2
Test Paper : 6
Power pack : 2
T-Shirt : 3
Cap : 5
Good, now we have qty and item_name.
Let's make queries. First look at your code:
$sql= $db->query("SELECT `stock` from `inventory` WHERE `item_name` = '$item_name'");
while ($sql1 = $sql->fetch_assoc()) {
$stock = $sql1['stock'];
}
Two strange things: 1) possible SQL injection, 2) replace $stock variable many times with new value (if we have more than 1 row for item in inventory).
Anyway, if this code is working (I can't check), then we come to next part:
if ($stock > $qty ) {
$stock_balance = $stock - $qty;
$quantity = (int)$qty;
$db->query("UPDATE `inventory` SET `stock` = (`stock` - '$quantity') WHERE `item_name` = '$item_name'");
} else {
echo "<h3> This Operation Not Allowed: Stock Balance Is Less Than The Request <h3>";
}
First, unnecessary cast to integer, so remove line $quantity = (int)$qty; and put $stock_balance into query. We will have:
if ($stock >= $qty ) {
$stock_balance = $stock - $qty;
$db->query("UPDATE `inventory` SET `stock` = $stock_balance WHERE `item_name` = '$item_name'");
} else {
echo "<h3> This Operation Not Allowed: Stock Balance Is Less Than The Request <h3>";
}
...well... not only you are exhausted, so I will end now. Ask if something is not correct or not understandable.

php remove duplicate values and show one

<?php
include ("../pos/db_config/db_config.php");
include ("../pos/functions/select.php");
$i = 0;
$sql = topsalep($idCompany);
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$end_sale_date = $row["end_sale_date"];
$name = $row["name"];
$tot_s = $row["tot_price"];
$qc = $row["sales_item_qty"];
$proResult[$i][0] = $name;
$proResult[$i][1] = $end_sale_date;
$proResult[$i][2] = $tot_s;
$proResult[$i][3] = $qc;
$i++;
}
//$name = $proResult[0][0];
//echo "$name";
for ($i = 0; $i < $result->num_rows; $i++) {
$count = 0;
$name = $proResult[$i][0];
$date = $proResult[$i][1];
$price = $proResult[$i][2];
$qct = $proResult[$i][3];
$totalPrice = 0;
for ($j = 0; $j < $result->num_rows; $j++) {
if ($proResult[$j][1] == $date && $proResult[$j][0] == $name) {
$x = $proResult[$j][2];
$count++;
$totalPrice+=$x;
}
}
$name = $proResult[$i][0];
$date = $proResult[$i][1];
$price = $proResult[$i][2];
for ($k = 0; $k < $count; $k++){
if($proResult[$k][1] == $date && $proResult[$k][0] == $name)
{
}
}
echo "Name : $name <br>";
echo "End Date : $date : Count $count : total = $totalPrice <br><br>";
?>
In this code I showed Last 5 days product vise total value. A one day can happen same sale id there different quantity of products. Then finally I calculated the one product wise total sale value. But problem is duplicate it.
In my join query I used distinct But I want show my PHP code when duplicated values only show one value.
enter image description here
enter image description here

PHP sum each loop value

I wanted to make a simple calculations to summarized what I purchased.
Using $_GET every time the value is updated it should save in an array then when 'start' is executed, it gives the sum. Sorry the codes here are just googled and I'm not really a programmer. I don't know how to combine the two sets of code (array + sum).
$number = $_GET ['input'];
$arr = array ($number);
$data = array($arr);
foreach ($tareas as $tarea) {
$data[] = $tarea;
}
var_dump($data);
$sum = 0;
foreach($group as $key=>$arr) {
$sum+= $arr;
}
echo $sum;
So I got this code from withinweb.com and modified to make it simpler.
<?php session_start();
$products = array($_GET["prod"]);
$amounts = array($_GET ["cost"]);
if ( !isset($_SESSION["total"]) ) {
$_SESSION["total"] = 0;
for ($i=0; $i< count($products); $i++) {
// $_SESSION["qty"][$i] = 0;
$_SESSION["amounts"][$i] = 0;
}
}
//---------------------------
//Reset
if ( isset($_GET['reset']) )
{
if ($_GET["reset"] == 'true')
{
unset($_SESSION["qty"]); //The quantity for each product
unset($_SESSION["amounts"]); //The amount from each product
unset($_SESSION["total"]); //The total cost
unset($_SESSION["cart"]); //Which item has been chosen
}
}
//---------------------------
//Add
if ( isset($_GET["add"]) )
{
$i = $_GET["add"];
$qty = $_SESSION["qty"][$i] + 1;
$_SESSION["amounts"][$i] = $amounts[$i] * $qty;
$_SESSION["cart"][$i] = $i;
$_SESSION["qty"][$i] = $qty;
}
//---------------------------
//Delete
if ( isset($_GET["delete"]) )
{
$i = $_GET["delete"];
$qty = $_SESSION["qty"][$i];
$qty--;
$_SESSION["qty"][$i] = $qty;
//remove item if quantity is zero
if ($qty == 0) {
$_SESSION["amounts"][$i] = 0;
unset($_SESSION["cart"][$i]);
}
else
{
$_SESSION["amounts"][$i] = $amounts[$i] * $qty;
}
}
//cart
if ( isset($_SESSION["cart"]) ) {
$total = 0;
foreach ( $_SESSION["cart"] as $i ) {
echo '' . $products[$_SESSION["cart"][$i]] . ' - ' . $_SESSION["amounts"][$i] . '<br>';
$total = $total + $_SESSION["amounts"][$i];
}
$_SESSION["total"] = $total;
echo'
<br>
Total : ' . $total . '
';
}
?>
When I input ?add=0&prod=apple&cost=100, it gives me:
apple - 100
Total : 100
But when I add another session, ?add=1&prod=orange&cost=200 it doesn't give the right answer.
orange - 100
- 0
Total : 100
It should return me this value, I'm puzzled where could be the error.
apple - 100
orange - 200
Total : 300
Yes, I'm not a coder, but trying to solve a big problem.. :) Thanks for those who help.

Decimals For negative PHP values

I am writing a bit of php code to output a random value
$max_mal = (3 - $oray);
$oray = 1;
$max = 100;
$total = 0;
for ($i = 0; $i < $max_mal; $i++){
$goli = mt_rand(3, 8);
$total += $goli;
$golis[] = $goli;
}
and for each loop goes here
foreach($golis as &$goli) {
$goli = floor(($goli / $total) * $max);
if ($goli == 0) {
$goli = 1;
}
}
$result = array_pad($golis, 3, -1);
shuffle($result);
$myresult = $result[0];
I am looking to get decimal values upto 5 numbers, but once a negative value comes it results out as 0.000-1 instead of -0.00001
$myresultb = str_pad($mario, 5, '0', STR_PAD_LEFT);
$myresultf = '0.'.$myresultb.'<br/>';
$total_score = 300;
echo $myresultf;
Secondly I am new to php learning so am I doing this PHP correct or it needs improvement
I have a div to show total score like this
<div id="total_score"></div>
and another div to show current score which value comes as echo $myresultf;
<div id="current_score"></div>
I want to update total score in real time with jquery wheneven button is clicked and <?php echo $myresultf ?> is refreshed in real time also
$("#play").click(function() {
var currentscore = $("#current_score").val();
var totalscore = $("#total_score").val();
how to do this.....
});
Try this:
$max = 100;
$oray = 1;
$max_mal = (3 - $oray);
$total = 0;
for ($i = 0; $i < $max_mal; $i++){
$goli = mt_rand(3, 8);
$total += $goli;
$golis[] = $goli;
}
foreach($golis as &$goli) {
$goli = floor(($goli / $total) * $max);
if ($goli == 0) {
$goli = 1;
}
}
$result = array_pad($golis, 3, -1);
shuffle($result);
$myresult = $result[0];
$negative_var=false;
if($myresult < 0)
{
$negative_var=true;
$myresult = 0-$myresult;
}
$myresultb = str_pad($myresult, 5, '0', STR_PAD_LEFT);
$myresultf = '0.'.$myresultb.'<br/>';
if($negative_var)
$myresultf="-".$myresultf;
$total_score = 300;
echo $myresultf;
simple use as follow:
$myresultb =str_replace('-','',$myresultb);
if($myresult == -1) {
$myresultf = '-0.'.$myresultb.'<br/>';
}
else {
$myresultf = '0.' . $myresultb . '<br/>';
}

PDO for loop issue

I have a function that should calculate prices based on quantity.
The function should loop through every order and calculate every product price based on quantity, then should return order total price.
What i'm doing wrong?
public function getSumaComanda($cos) {
$suma = $this->_db->query(sprintf("SELECT (#pretredus:=`pretredus`) AS `pretredus`,(CASE #pretredus WHEN 0 THEN `prettotal` ELSE `pretredus` END) AS `prettotal` , cantitate FROM comenzi WHERE cos = '%d'", $cos));
$suma->execute();
$data_array = $suma->fetchAll(PDO::FETCH_ASSOC);
$count = $this->_db->query(sprintf("SELECT COUNT(*) FROM cosuri WHERE id='%d'", $cos));
$num = $count->fetchColumn();
for ($x = 0; $x < $num; $x++) {
$price = $data_array['cantitate'][$x] * $data_array['prettotal'][$x];
$pret = $pret + $price;
$pret = number_format($pret, 2, ".", "");
}
$rez = $pret;
return $rez . ' Lei';
}
You should learn how to basically debug your variables. With using var_dump($data_array); you can see, what's in there.
You have to use the numerical index first:
$price = $data_array[$x]['cantitate'] * $data_array[$x]['prettotal'];
Nevertheless, your second query is useless. You don't have to count the results and can use instead a while-loop:
public function getSumaComanda($cos) {
$suma = $this->_db->query(sprintf("SELECT (#pretredus:=`pretredus`) AS `pretredus`,(CASE #pretredus WHEN 0 THEN `prettotal` ELSE `pretredus` END) AS `prettotal` , cantitate FROM comenzi WHERE cos = '%d'", $cos));
$suma->execute();
while ($data_array = $suma->fetch(PDO::FETCH_ASSOC)) {
$pret += $data_array['cantitate'] * $data_array['prettotal'];
}
return number_format($pret, 2, ".", "") . ' Lei';
}

Categories