I’m not a programmer but in the past I have tinkered with other people’s code to reasonable effect.
As part of a freelance job, I’ve inherited a very simple PHP-based shopping cart, with no SQL buddy present. I’m clueless about SQL so this wouldn’t be an option.
Stock data is contained in a tab-delimited text file that contains stuff like product name, stock id, price, postage, etc. The shop PHP deconstructs this when the page loads, and assigns session array/variable names to each part of the stock table. The cart file then uses session variables to add/remove products, and the checkout part sends a bunch of totalled variables to PayPal.
The client is asking me to make a change to this: where currently each product bears a postage price, and it all gets totalled up and sent to PayPal, what he wants is that each product bears a weight, and the script totals up all product weights, then refers to a table of weight thresholds to calculate the total postage value.
So, I can conceptually work out what to do, and will be able to get about 80% of the way there, but know of no elegant way to create a lookup of the above table (which will necessarily be a txt file or embedded into the PHP) without using dozens of nested IF statements. Is there some kind of thing that checks a number and compares it with numbers in an array, then establishes if it’s larger than one part of array and smaller than the other part?
If there were a thousand such decisions to make I’d say ‘divide and conquer’, maybe with a binary tree. In this case, just go with the ‘if’ statements.
Does PHP allow hashes? I think it’s an offshoot of Perl, and if I had to do this all self-contained in Perl I’d probably do a hash of hashes where the outer key is a pre-defined postal amount, and the inner hash is an upper bound and lower bound for that range. So you could iterate a loop through your keys, sorted ascending, and then do one comparison per loop to see if it was within the range for that postal amount. If you run through the loop and you don’t have a winner, then it’s over the maximum and you apply the last value(highest) plus the extra.
Thanks all, especially Sofis. I cracked it myself, and have tested the following at all weights - it works, even for for weights greater than 2kg up to 4kg.