PHP Session Array Update - php

I wish to update a single product quantity from a session with a new value using php.
How can I do this.
Array data is as displayed
Array
(
[products] => Array
(
[0] => Array
(
[name] => Ford AA Flatbed
[code] => IWV001
[qty] => 1
[price] => 15.00
[weight] => 0.12
)
[1] => Array
(
[name] => Ford AA Stakebed
[code] => IWV003
[qty] => 1
[price] => 15.00
[weight] => 0.21
)
)
)
any help would be most appreciated.
I want to be able to search through the session and find the product by code and update the quantity within that product.

Something like this:
foreach($products as &product) {
if ($product[code] == $codeToUpdate) {
$product[qty] = $newQty;
}
}
Of course, this is a sequential search so it will be slow for large data sets.

Related

Get value multidimensional array and combine product group

I have created a multidimensional array using a csv file.
I get the following array:
Array
(
[0] => Array
(
[0] => Product
[1] => Price
[2] => Quantity
[3] => Date
)
[1] => Array
(
[0] => Teddybear
[1] => 3.789,33
[2] => 2
[3] => 2018-08-14
)
[2] => Array
(
[0] => Teddybear
[1] => 2.702,17
[2] => 1
[3] => 2018-02-17
)
[3] => Array
(
[0] => Table
[1] => 2.932,29
[2] => 5
[3] => 2018-10-09
)
[4] => Array
(
[0] => Lamp
[1] => 671,70
[2] => 3
[3] => 2018-12-11
)
[5] => Array
(
[0] => Teddybear
[1] => 481,21
[2] => 3
[3] => 2018-03-24
)
[6] => Array
(
[0] => Table
[1] => 456,52
[2] => 3
[3] => 2018-05-14
)
[7] => Array
(
[0] => Chair
[1] => 2.960,20
[2] => 2
[3] => 2018-06-20
)
[8] =>
)
I need to create a json file, but before that, I need to count al products and turnover per month
I'm a novice / junior PHP developer and I'm more specialized in WordPress, so forgive me for my bad code and/or bad practices. I'm here to learn.
I really don't know how to select for example all the Teddybears. I know I could do $csv[1][1]; to select turnover for the first Tedybear.
ok here there should be everything you need, I did 3 functions that you can chain together to get what you need, like in the example
$data=[
["Product","Price","Quantity","Date"], // <-- if you want to remove the header remove all the lines with this symbol *
["Teddybear",3789.33,2,"2018-08-14"],
["Teddybear",2702.17,1,"2018-02-17"],
["Table",2932.29,5,"2018-10-09"],
["Lamp",671.70,3,"2018-12-11"],
["Teddybear",481.21,3,"2018-03-24"],
["Table",45.52,3,"2018-05-14"],
["Chair",2960.20,2,"2018-06-20"]
];
function WhereFromColum($data,$colum,$equal){
$ret=[];
array_push($ret,$data[0]); // *
$colum = is_numeric($colum)?$colum:array_search($colum,$data[0]);
for($i=1/* 0 if you remove the header to data*/;$i!=count($data);$i++)
if ($data[$i][$colum]==$equal)
array_push($ret,$data[$i]);
return $ret;
}
function CountFromColum($data,$colum){
$ret=0;
$colum = is_numeric($colum)?$colum:array_search($colum,$data[0]);
for($i=1/* 0 if you remove the header to data*/;$i!=count($data);$i++)
$ret+=$data[$i][$colum];
return $ret;
}
function WhereFromColumData($data,$colum,$min,$max){
$contractDateBegin = new DateTime($min);
$contractDateEnd = new DateTime($max);
$ret=[];
array_push($ret,$data[0]); // *
$colum = is_numeric($colum)?$colum:array_search($colum,$data[0]);
for($i=1/* 0 if you remove the header to data*/;$i!=count($data);$i++){
$paymentDate = new DateTime($data[$i][$colum]);
if ($paymentDate->getTimestamp() > $contractDateBegin->getTimestamp() &&
$paymentDate->getTimestamp() < $contractDateEnd->getTimestamp())
array_push($ret,$data[$i]);
}
return $ret;
}
var_dump(WhereFromColum($data,"Product","Teddybear")); // get all Teddybear's Product
var_dump(CountFromColum($data,"Quantity")); // get all Quantity
var_dump(CountFromColum(WhereFromColum($data,"Product","Teddybear"),"Quantity")); // get all Quantity of Teddybear's Product
var_dump(WhereFromColumData($data,"Date","2018-08-01","2018-12-01")); // get all between 2018-08-01 and 2018-12-01
var_dump(WhereFromColumData(WhereFromColum($data,"Product","Teddybear"),"Date","2018-08-01","2018-12-01")); // get all Teddybear's Product between 2018-08-01 and 2018-12-01
usually I don't usually write code but explain how to do it but in your case it was too complex so please kindly read the three functions carefully and try to understand how they work, ps if you want to improve your skils in php I suggest you play a with these functions and modify them to fit what you need best. when you understand how they work you can also create another one with the same logic of nesting that allows you to make much more advanced filters.

How to make an array from the deference between two arrays?

I am making an online shopping cart. so I want to update my total stock after confirming my products... I am able to catch the quantity from the user and i am able to catch my data from MYSQL. Now i want to make an array from the difference between my MYSQL quantity and user quantity and update my total stock after purchase...
My MYSQL ARRAY OUTPUT IS:
print_r($qty);
Array ( [0] => Array ( [stock] => 100 ) [1] => Array ( [stock] => 100 ) [2] => Array ( [stock] => 50 ) [3] => Array ( [stock] => 100 ) )
and
my user ARRAY OUTPUT IS:
print_r ($_SESSION['productqty']);
Array ( [0] => 10 [1] => 12 [2] => 14 [3] => 16 )
I want to make an array which will be like
Array ( [0] => 90 [1] => 88 [2] => 36 [3] => 84 )
This array is the difference between the two arrays and it will be updated in the MYSQLI Query...
I have Tried Everything. Please Help me...
If the indexes are equal the following code could work:
$remaining = [];
// iterate $qty rows and fill $remaining array
foreach($qty as $index => $entry) {
$remaining[] = $entry['stock'] - $_SESSION['productqty'][$index];
}
var_dump($remaining);
EDIT: Store updated stock in database
Firstly it's necessary to select products' ids in your first query so that you're able to update them later. This step should result the following dump (apart from the correct ids)
Array (
[0] => Array ( [id] => 12, [stock] => 100 )
[1] => Array ( [id] => 37, [stock] => 100 )
[2] => Array ( [id] => 39, [stock] => 50 )
[3] => Array ( [id] => 50, [stock] => 100 )
)
Now you can optimize your calculation by attaching the products' ids to your array:
remaining = [];
foreach($qty as $index => $entry) {
$remaining[] = [
'id_product' => $entry['id'],
'stock' => $entry['stock'] - $_SESSION['productqty'][$index]
];
}
Now you're able to store your updated stocks:
foreach($remaining as $entry) {
// Perform your SQL-Operation, something like:
// UPDATE products SET stock = $entry['stock'] WHERE id = '$entry['id']
}
Attention: Please secure your application against SQL-Injections.
Take a look at: https://en.wikipedia.org/wiki/SQL_injection

generating an array out of another array by using a unique key

I have an array that contains 3 products with attributes of "color" and "size" and the products are identified by a number ( ['code'] ).
My problem is that when i pull the data from the database I get this array that is in 6 pieces because "color" and "size" get stored in separate arrays.
My question is, how do I generate the data into an array of these 3 products with all their data in the same array.
Array(
[0] => Array
(
[code] => 123
[name] => box
[stock] => 2.00
[price] => 10.00
[color] => brown
)
[1] => Array
(
[code] => 123
[name] => box
[stock] => 2.00
[price] => 10.00
[size] => L
)
[2] => Array
(
[code] => 1234
[name] => box
[stock] => 3.00
[price] => 11.00
[color] => brown
)
[3] => Array
(
[code] => 1234
[name] => box
[stock] => 3.00
[price] => 11.00
[size] => XL
)
[4] => Array
(
[code] => 12345
[name] => box
[stock] => 4.00
[price] => 12.00
[size] => XL
)
[5] => Array
(
[code] => 12345
[name] => box
[stock] => 4.00
[price] => 12.00
[color] => gray
)
)
Expected output:
[0] => Array
(
[code] => 123
[name] => box
[stock] => 4.00
[price] => 12.00
[color] => gray
[size] => XL
)
What i'm looking to do is just combine the doubled array into one. Dont want to mess with SQL anymore - it gets attribute name in one table, attribute values from another table, code,stock,price from another table, name from another table. I know something can be done with just this array even if it will be just a temporary solution.
You can do this:
assuming your array is $products
$merged = array();
foreach($products as $product) {
if (!isset($sorted[$product['code']])) {
$merged[$product['code']] = $product;
} else {
$merged[$product['code']] = array_merge($sorted[$product['code']], $product);
}
}
Use the product code as array key and then merge the array.
If the two rows are always direct successors, with the first one holding the color field, while the latter holes the size field, you can make it easily by iterating over them in a for loop:
$maxCount = count($array);
for ($i = 1; $i < $maxCount; $i += 2) {
$array[$i - 1]['size'] = $array[$i]['size'];
unset($array[i]);
}
This will iterate over each second element of the array and add the size field to the preceding field.
If you need to have succeeding array keys afterwards you can call $arry = array_values($array);.
In case the the associated rows might not be successors you need to map them based on their code field (in case thats the primary key). You can use array_reduce() for that:
$desiredOutput = array_reduce($array, function($output, $element) {
if (!array_key_exists($element['code'], $output)) {
$output[$element['code']] = $element;
} elseif (array_key_exists('size', $element)) {
$output[$element['code']]['size'] = $element['size'];
} elseif (array_key_exists('color', $element)) {
$output[$element['code']]['color'] = $element['color'];
}
return $output;
}, []);

check if cart item has the same property

Am using the codeigniter cart library, but now the client wants users to only be able to checkout items from one category at at a time because of some issues with their payment gateway.
Current the site has a single checkout logic for all categories.
When a users adds an items to the cart, i have an array like this
Array
(
[d8df18561040f3d9bd9868f5c5aaa7c2] => Array
(
[rowid] => d8df18561040f3d9bd9868f5c5aaa7c2
[id] => MYU_SC1
[qty] => 1
[price] => 500
[name] => WAEC Scratch Card
[service_image] => assets/img/waec.jpg
[service_category] => scratch_cards
[subtotal] => 500
)
[99483fe03da62c9e98ce71232998f447] => Array
(
[rowid] => 99483fe03da62c9e98ce71232998f447
[options] => Array
(
[size] => 36
[colour] => N/A
)
[id] => 80433426a546064bf5f8d09a6e7fdabc
[qty] => 1
[price] => 5000
[name] => Green Vee Jeans
[service_image] => http://localhost/myunivacity/uploads/apparels/IMG_0425.JPG
[service_category] => apparels
[subtotal] => 5000
)
)
how i do check if whether or not the items in the cart have same value for "service_category" element?. Thanks for the help
You could go with something like this:
<?php
$categories = array();
foreach($this->cart->contents() as $cart_item) {
if(!isSet($categories[$cart_item["service_category"]]) {
$categories[$cart_item["service_category"]] = 1;
}
else {
$categories[$cart_item["service_category"]]++;
}
}
print_r($categories);
?>
This fills an array with a count per category

Searching php arrays

I have a PHP array question regarding searching which I'm hoping some kind person can help me with...
The array shown below is an collection of arrays, e.g. order items. As I loop a separate array of orderIds I would like to return the appropriate array of products.
For example, if I request an orderId of 98305 it would return the arrays with the indexes of 2 & 3.
Are there any PHP functions to do this? I could loop each array and check the value and break out when it matches, but I feel this brings quite an overhead of performing multiple loops per orderId lookup.
Array
(
[0] => Array
(
[orderId] => 98303
[product] => Product A
)
[1] => Array
(
[orderId] => 98304
[product] => Product B
)
[2] => Array
(
[orderId] => 98305
[product] => Product C
)
[3] => Array
(
[orderId] => 98305
[product] => Product D
)
[4] => Array
(
[orderId] => 98306
[product] => Product A
)
[5] => Array
(
[orderId] => 98306
[product] => Product B
)
)
Any help appreciated.
D
array_filter()
$output = array_filter($input,function($a) {
return $a['orderId'] == 98305;
});
Replace 98305 with the desired ID.

Categories