I am writing some code to supply the Google certified shop data which I have nearly finished. I only need to supply the ship and delivery dates. I have written code to supply this information at the product level. However when there is more than one product in an order I need to select the largest ship date.
For example;
Order has two products.
Producta with $ship_date = 2 and porductb with $ship_date = 5
I need to collect all the $ship_dates (2 and 5) and return the highest one (5).
My question is simply how do I write the php to collect all the $ship_dates correctly - should I create an array and if so how?
Put all the required variables into an array, then use max.
$ship_date1 = 2;
$ship_date2 = 5;
$shipDates = [$ship_date1, $ship_date2];
// other dates as needed
// OR, a much cleaner solution, append to the array
$shipDates = [];
$shipDates[] = 2;
$shipDates[] = 5;
//No matter how you fill up the array, this is how you get its maximum value
$maxShipDate = max($shipDates);
max actually accepts individual variables instead (eg. max($ship_date1, $ship_date2);) but the array solution is easier to maintain.
OK before my foreach product loop I added this;
$deliverydatearray = array();
which creates a new (empty) array which I called $deliverydatearray
Within my foreach product loop I added this;
$deliverydatearray[] = $delivery_datep;
which adds my product specific delivery date ($delivery_datep) to my array.
After the foreach product loop has closed I can access the variables in my array. For example just printing the contents of the array is done like this;
print_r($deliverydatearray);
which looks like this;
Array
(
[0] => 2017-01-28
[1] => 2017-01-23
)
Related
I have a SESSION['cart'] with ID numbers only. I have a form passing the ID with a remove button. Once passed to my controller, I cannot figure out how to write the code that uses the ID ($_POST['id']) to delete the item from the SESSION['cart'].
I can loop through and display the array contents, but I cannot figure out how to delete based on ID passed from the form.
How do I loop through the SESSION['cart'] array to find a match with the ID passed from my delete form, and then delete that ID? I know that unset($_SESSION['cart'][X] deletes the ID at index X, but I cannot figure out how to loop through all the elements to find a match.
I have read a number of related issues in this forum but have been unable to apply any of those solutions to resolve this challenge. Any assistance is appreciated.
The way you have your values ($products = array(3,7,99,152)) isn't a very good method. Every time you want to perform an action, you have to loop through the array, you don't want that. Apart from that, how do you store quantity? Or variations like e.g. size or color?
if your structure is $array[ ID_OF_PRODUCT ], you can simply do this:
unset( $_SESSION['cart'][$_POST['id']] ); // Instant access via the key!
This should be the method to use. This allows you to create an array like this, with advanced info, but with easy access (42/63 are example id's)
$_SESSION['cart']['products'][42] = array(
'quantity' = 11,
'size' = 'large',
'color' = 'blue'
);
$_SESSION['cart']['products'][63] = array(
'quantity' = 9,
'size' = 'small',
'color' = 'red'
);
This way you can access a lot of info with the product ID, and now also see which size and color (both just examples) the user selected. You may not have need for this now, but you will further down the road :)
As you might see, you can easily do stuff with the item:
isset($_SESSION['cart'][$_POST['id']]); // check if the product exists
unset($_SESSION['cart'][$_POST['id']]); // remove the product
echo $_SESSION['cart'][$_POST['id']]['quantity']; // get the quantity.
Not a loop in the code. You should only use loops when you have to, try to somewhat avoid them because often their slow. Say you have an extreme case of 1000 items in your shop, and you need to delete no999... That'll take a noticable moment.
Here is the code to do it right:
$id = $_POST['id'];
$items = $_SESSION["cart"];
if(($key = array_search($id, $items)) !== false) {
unset($items[$key]);
}
$_SESSION["cart"] = array_values($items);
Advice
Beside item ID, you can also sve item count in SESSION array because user can add several times same item into cart. In that case your $_SESSION["card"] should be structured like:
array(
'1'=>12,//Item with ID=1 is added 12 times in shopping cart
'17'=>2,//Item with ID=17 is added 2 times in shopping cart etc.
'32'=>12,
)
Bit stuck on how to achieve this.....
I have a PHP page which shows information for one record in a table. These records include a unique key (image_id) AND a name (image_name).
In order to display the correct record, I am using a search function on a previous page which results in a URL parameter (imageinfo.php?image_id=1 etc).
My problem is that I wish to add forward and back arrows to the table to cycle through different records, BUT based on the alphabetical order of 'image_name' rather than the numerical order of 'image_id.
I'm really not sure how to achieve this, so any help would be appreciated.
Something like this: (I hope the comments will explain)
<?php
$data = array(
123 => "B",
321 => "C",
124 => "A"
);
$id = 123; // This is the current image id
asort($data); // Sort the array based on values (names)
// Advance the internal pointer until it points to the current image
while(current($data) != $data[$id])
next($data);
// TODO: Also check whether next is past end here
echo next($data); // Should be C
I have list of items that need to be processed and printed to the user.
Each item on the list needs to have a unique set of calculations to it.
The only thing is, the user also supplies me with the order of how items will be printed & handled first - for example: item4,item2,item1,item3
How can one approach this in PHP?
I thought of running a for loop against the user submitted ordered list and tackle each calculation and print it to the user, the problem is that this will be hard to maintain because the user will have to edit the for loop each time he will want to add a new item or calculation.
Given a list of 1-n items:
$items['item1'] = $item1;
With a co-related list of 1-n functions:
$functions['item1'] = function($item) {return ...;};
You can sort items according to the user-input:
$subset = orderAndFilterItems($items, $userInput);
and then iterate:
foreach($subset as $key => $item)
{
$function = $functions[$key];
$value = $function($item);
}
Naturally you can encapsulate this further on, but it should give you the idea.
I have a shopping cart type arrangement. The customer builds the order in tiers. So page one is item 1, page 2 item 2....... The page does not reload during the building of a order. (jqtouch) My way of building the order is add each item to an array. Below is how I have created the array.
var item_contents= new Array();
so typical order with two items would look something like..
item_contents[0] = 627
item_contents[1] = 451
item_contents[2] = 365
item_contents[3] = 548
item_contents[4] = 158
item_contents[5] = 154
item_contents[6] = 155
item_contents[7] = 115
The number is the item_id number in a database. The user has the ability to go back and alter an item in the array for the current order.
When the checkout screen is shown this needs to be submitted and details for the respective item_id returned. I guess the best way would be someway to replicate the array above in php. How Would I POST an array like this and get it to look identical in php?
Thx
jquery post
var a = [627,451,365,548,158,115,155,115];
$.post("ajax.php",{data: a},function(data){
console.log(data);
});
php
<?php
$array = json_decode($_POST['data']);
foreach($array as $key => $value){
add(sanitize($value[$key]));
}
?>
I'm trying to create an array to display the last 5 products a customer has viewed.
The array is a 2 dimensional array like below...
$RView= array(
array( ID => "1001", RefCode => "Ref_01", Name => "Name_01" ),
...
array( ID => "1005", RefCode => "Ref_05", Name => "Name_05" )
);
The array values are retrieved from the products recordset and is designed to function as follows when a customer visits a product page.
Page will check if a Session Array exists
If yes, an array variable is created from existing Session
If no, a new array is created.
Array will add the new product details.
Array will count if there are more than 5 existing products in the array.
If yes, it will remove the oldest.
If no, moves to next step.
A Session is created/updated from the revised Array.
My current effort is attached below...
Many thanks for any help.
<?php
session_start()
// Get or Create Array
IF (isset($_SESSION['sessRView'])) {
$RView = ($_SESSION['sessRView']); }
ELSE {
$RView = array(array());
}
// Append currently viewed Product to Array
array(array_unshift($RView, $row_rsPrd['PrdID'], $row_rsPrd['RefCode'], $row_rsPrd['Name']));
// Check if more than 5 products exist in Array, if so delete.
IF (sizeof($RView) > 5) {
array(array_pop($RView)); }
// Update Session for next page
$_SESSION['sessRView'] = $RView;
// Display Array
for ($row = 0; $row < 5; $row++)
{
echo "<ul>";
echo "<li><a href='?PrdID=".$RView[$row]["PrdID"]."'>".$RView[$row]["RefCode"]."</a> : ".$RView[$row]["Name"]."</li>";
echo "</ul>";
}
?>
It's more or less right - just 2 lines need to be changed.
There's no need for the extra array() around array_unshift and array_pop.
When you use array_unshift you're pushing an array of items (not the id/codes individually) - I think you mean array_unshift($RView, array($prodid,$name,...))
What if $RView doesn't have 5 elements? In that case you're accessing undefined array indices (which may or may not show an error). Change it to a foreach loop: e.g.
foreach ($Rview as $prod) echo $prod['Name']...
It should work after you make these changes. You might want to clean up the coding style a bit, though :)
EDIT: Oh, I see, when you're referencing the array in the for loop it doesn't know that the array has "ProdID" and "Name" indices. When you make an array you have to define the indexes using the => operator.
Add indexes to the array when you array_unshift:
array_unshift($RView, array("ProdID" => $row_rsProd["ProdID"], "Name"...))
If row_rsProd isn't too big, you can just tack the entire row_rsprod onto $RView.
so change array_unshift(...) to just $RView[] = $row_rsProd
This way the indexes are preserved.
Alternatively you can change the indicies in the for loop to match. Right now the array you unshift onto $RView is 0-based - $RView[0][0] is the product ID for the first product, etc.
So you can change the stuff in the foreach loop to
echo "<li>..." $prod[0] $prod[1] $prod[2]
Hope that helps!