How to do operations on nested nested arrays - php

I need to loop through all pending orders "DONE"
then loop through each order items and save them to an array DONE
then call the api which will return a response like this DONE
{"response":
[{"Lookup":"SKU","Quantity":3,"StoreName":"Shop1"},
{"Lookup":"SKU","Quantity":30,"StoreName":"Shop2"},
{"Lookup":"SKU","Quantity":15,"StoreName":"Shop3"},
{"Lookup":"SKU","Quantity":50,"StoreName":"Shop4"}]}
after that i need to check the quantity from Shop3 first, if it is bigger than the ordered amount, then take it from there and save the new quantity, if there is still remaining quantity, then loop through the rest of the shops, and take from the shop that have the most quantity, and this where I'm Stuck. if I looped through all stores and there is still quantity to get ordered, i should report it too.
What I have done so far is this.
$requiredItems--> is an array of (sku => Ordered Quantity) which is accurate
$report = array();
$allItemsStoreQty = array();
$unavailableItems = array();
foreach ($requiredItems as $sku => $qty) {
$remainingQty = $qty;
$itemStoreQty = array();
//Get Stock Breakdown
$stock = $this->getStock($sku);
if ($stock['Shop3'] >= $qty) {
$storeQty = array();
$storeQty['Shop3'] = $qty;
array_push($itemStoreQty, $storeQty);
} else {
if ($stock['Shop3'] < $qty) {
$storeQty = array();
$storeQty['Shop3'] = $qty;
$remainingQty = $qty - $stock['Shop3'];
$stock['Shop3'] = 0;
array_push($itemStoreQty, $storeQty);
}
arsort($stock);
foreach ($stock as $storeStockName => $storeStockQty) {
if ($remainingQty > 0 && $storeStockQty > 0) {
$currentQty = $remainingQty - $storeStockQty;
if ($currentQty <= 0) {
$storeQty = array();
$storeQty[$storeStockName] = $remainingQty;
array_push($itemStoreQty, $storeQty);
$remainingQty = 0;
} else {
$storeQty = array();
$storeQty[$storeStockName] = $currentQty;
array_push($itemStoreQty, $storeQty);
$remainingQty = $currentQty;
}
}
}
$allItemsStoreQty[$sku] = $itemStoreQty;
}
if ($remainingQty > 0) {
$unavailableItems[$sku] = $remainingQty;
}
}
$report['available'] = $allItemsStoreQty;
$report['unavailable'] = $unavailableItems;
return $report;
but the report that is coming in wrong numbers, I don't know where is my mistake, I know it's somewhere in the logic :( But I can't find it.

as far as i can see, the problem is:
if ($stock['Shop3'] >= $qty) {
$storeQty = array();
$storeQty['Shop3'] = $stock['shop3']; // not $qty
array_push($itemStoreQty, $storeQty);
}
and
} else {
$storeQty = array();
$storeQty[$storeStockName] = $storeStockQty; // not $currentQty;
array_push($itemStoreQty, $storeQty);
$remainingQty = $currentQty;
}

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 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.

PHP evaluating the content of an array

I am trying to evaluate the content of an array. The array contain water temperatures submitted by a user.
The user submits 2 temperaures, one for hot water and one for cold water.
What I need is to evaluate both array items to find if they are within the limits, the limits are "Hot water: between 50 and 66", "Cold water less than 21".
If either Hot or Cold fail the check flag the Status "1" or if they both pass the check flag Status "0".
Below is the code I am working with:
$row_WaterTemp['HotMin'] = "50";
$row_WaterTemp['Hotmax'] = "66";
$SeqWaterArray new(array);
$SeqWaterArray = array("58", "21");
foreach($SeqWaterArray as $key => $val) {
$fields[] = "$field = '$val'";
if($key == 0) {
if($val < $row_WaterTemp['HotMin'] || $val > $row_WaterTemp['Hotmax']) {
$Status = 1;
$WaterHot = $val;
} else {
$Status = 0;
$WaterHot = $val;
}
}
if($key == 1) {
if($val > $row_WaterTemp['ColdMax']) {
$Status = 1;
$WaterCold = $val;
} else {
$Status = 0;
$WaterCold = $val;
}
}
}
My question is:
When I run the script the array key(0) works but when the array key(1) is evaluted the status flag for key(1) overrides the status flag for key0.
If anyone can help that would be great.
Many thanks for your time.
It seems OK to me, exept for the values at limit, and you can simplify
$row_WaterTemp['HotMin'] = "50";
$row_WaterTemp['Hotmax'] = "66";
$SeqWaterArray = array("58", "21");
$Status = array() ;
foreach($SeqWaterArray as $key => $val) {
if($key == 0) {
$Status = ($val >= $row_WaterTemp['HotMin'] && $val <= $row_WaterTemp['Hotmax']) ;
$WaterHot = $val;
} else if($key == 1) {
$Status += ($val >= $row_WaterTemp['ColdMax']) ;
$WaterCold = $val;
}
}
If one fails, $Status = 1, if the two tests failed, $Status = 2, if it's ok, $Status = 0.
<?php
// this function return BOOL (true/false) when the condition is met
function isBetween($val, $min, $max) {
return ($val >= $min && $val <= $max);
}
$coldMax = 20; $hotMin = 50; $hotMax = 66;
// I decided to simulate a test of more cases:
$SeqWaterArray['john'] = array(58, 30);
$SeqWaterArray['martin'] = array(34, 15);
$SeqWaterArray['barbara'] = array(52, 10);
foreach($SeqWaterArray as $key => $range) {
$flag = array();
foreach($range as $type => $temperature) {
// here we fill number 1 if the temperature is in range
if ($type == 0) {
$flag['hot'] = (isBetween($temperature, $hotMin, $hotMax) ? 0 : 1);
} else {
$flag['cold'] = (isBetween($temperature, 0, $coldMax) ? 0 : 1);
}
}
$results[$key]['flag'] = $flag;
}
var_dump($results);
?>
This is the result:
["john"]=>
"flag"=>
["hot"]=> 1
["cold"]=> 0
["martin"]=>
"flag" =>
["hot"]=> 1
["cold"]=> 0
["barbara"]=>
"flag" =>
["hot"]=> 0
["cold"]=> 0
I don't think that you need a foreach loop here since you are working with a simple array and apparently you know that the first element is the hot water temperature and the second element is the cold water temperature. I would just do something like this:
$row_WaterTemp['HotMin'] = 50;
$row_WaterTemp['HotMax'] = 66;
$row_WaterTemp['ColdMax'] = 21;
$SeqWaterArray = array(58, 21);
$waterHot = $SeqWaterArray[0];
$waterCold = $SeqWaterArray[1];
$status = 0;
if ($waterHot < $row_WaterTemp['HotMin'] || $waterHot > $row_WaterTemp['HotMax']) {
$status = 1;
}
if ($waterCold > $row_WaterTemp['ColdMax']) {
$status = 1;
}
You can combine the if statements of course. I separated them because of readability.
Note that I removed all quotes from the numbers. Quotes are for strings, not for numbers.
You can use break statement in this case when the flag is set to 1. As per your specification the Cold water should be less than 21, I have modified the code.
<?php
$row_WaterTemp['HotMin'] = "50";
$row_WaterTemp['Hotmax'] = "66";
$row_WaterTemp['ColdMax'] = "21";
$SeqWaterArray = array("58", "21");
foreach($SeqWaterArray as $key => $val) {
$fields[] = "$key = '$val'";
if($key == 0) {
if($val < $row_WaterTemp['HotMin'] || $val > $row_WaterTemp['Hotmax']) {
$Status = 1;
$WaterHot = $val;
break;
} else {
$Status = 0;
$WaterHot = $val;
}
}
if($key == 1) {
if($val >= $row_WaterTemp['ColdMax']) {
$Status = 1;
$WaterCold = $val;
break;
} else {
$Status = 0;
$WaterCold = $val;
}
}
}
echo $Status;
?>
This way it would be easier to break the loop in case if the temperature fails to fall within the range in either case.
https://eval.in/636912

Retrieve All Data From One Table in Database into Array and Calculate it

Related to question from this Pearson correlation in PHP , now I'm using that function too for calculate similarity between 2 users with pearson correlation. What I wanna ask is :
I have database name ta_db
And I want to retrieve data from table interest which have 9 attributes into array
After that I want to calculate it with pearson correlation function.
public function similarity($user1, $user2) {
$sharedItem = array();
$pref1 = array();
$pref2 = array();
$result1 = $user1->fetchAllPreferences();
$result2 = $user2->fetchAllPreferences();
foreach($result1 as $pref){
$pref1[$pref->item_id] = $pref->rate;
}
foreach($result2 as $pref){
$pref2[$pref->item_id] = $pref->rate;
}
foreach ($pref1 as $item => $preferenza){
if(key_exists($item,$pref2)){
$sharedItem[$item] = 1;
}
}
$n = count($sharedItem);
if ($n == 0) return 0;
$sum1 = 0;$sum2 = 0;$sumSq1 = 0;$sumSq2 = 0;$pSum = 0;
foreach ($sharedItem as $item_id => $pre) {
$sum1 += $pref1[$item_id];
$sum2 += $pref2[$item_id];
$sumSq1 += pow($pref1[$item_id],2);
$sumSq2 += pow($pref2[$item_id],2);
$pSum += $pref1[$item_id] * $pref2[$item_id];
}
$num = $pSum - (($sum1 * $sum2) / $n);
$den = sqrt(($sumSq1 - pow($sum1,2)/$n) * ($sumSq2 - pow($sum2,2)/$n));
if ($den == 0) return 0;
return $num/$den;
}
From my explanation above, could you please tell me how to retrieve the data into Array? Thank you in advance for your help and clear explanation.

Pseudo-code for shelf-stacking

Suppose I have some serially numbered items that are 1-n units wide, that need to be displayed in rows. Each row is m units wide. I need some pseudo-code that will output the rows, for me, so that the m-width limit is kept. This is not a knapsack problem, as the items must remain in serial number order - empty spaces at the end of rows are fine.
I've been chasing my tail over this, partly because I need it in both PHP and jQuery/javascript, hence the request for pseudo-code....
while (!items.isEmpty()) {
rowRemain = m;
rowContents = [];
while (!items.isEmpty() && rowRemain > items[0].width) {
i = items.shift();
rowRemain -= i.width
rowContents.push(i);
}
rows.push(rowContents);
}
Running time is Θ(number of items)
Modulus is your friend. I would do something like:
$items = array(/* Your list of stuff */);
$count = 0;
$maxUnitsPerRow = 4; // Your "m" above
while ($item = $items[$count]) {
if ($count % $maxUnitsPerRow == 0) {
$row = new row();
}
$row->addItemToRow($item);
$count++;
}
Here is an alternative php code ...
function arrayMaxWidthString($items, $maxWidth) {
$out = array();
if (empty($items)) {
return $out;
}
$row = $maxWidth;
$i = 0;
$item = array_shift($items);
$row -= strlen($item);
$out[0] = $item;
foreach ($items as $item) {
$l = strlen($item);
$tmp = ($l + 1);
if ($row >= $tmp) {
$row -= $tmp;
$out[$i] = (($row !== $maxWidth) ? $out[$i] . ' ' : '') . $item;
} elseif ($row === $maxWidth) {
$out[$i] = $item;
++$i;
} else {
++$i;
$row = $maxWidth - $l;
$out[$i] = $item;
}
}
return $out;
}
For what it's worth, I think I have what I was looking for, for PHP - but not sure if there is a simpler way...
<?php
// working with just a simple array of widths...
$items = array(1,1,1,2,1,1,2,1);
$row_width = 0;
$max_width = 2;
echo "Begin\n"; // begin first row
foreach($items as $item=>$item_width) {
// can we add item_width to row without going over?
$row_width += $item_width;
if($row_width < $max_width) {
echo "$item_width ";
} else if($row_width == $max_width) {
echo "$item_width";
echo "\nEnd\nBegin\n"; // end last row, begin new row
$row_width = 0;
} else if($row_width == 2* $max_width) {
echo "\nEnd\nBegin\n"; // end last row, begin new row
echo "$item_width";
echo "\nEnd\n"; // end new row
$row_width = 0;
if($item < count($items)) echo "Begin\n"; // new row
} else if($row_width > $max_width) {
echo "\nEnd\nBegin\n"; // end last row, begin new row
echo "$item_width";
$row_width = $item_width;
}
}
echo "\nEnd\n"; // end last row
?>

Categories