 # PHP arrays (manipulation, merging...)

Hi experts,

spent most of my day trying to find a solution for this, no avail.
Should be easy for somebody who has got a bit of experience with PHP arrays, I think.

In PHP, I have a two dimensional array:

\$array=array("A","1","10","5.00")
\$array=array("A","2","10","9.00")
\$array=array("A","4","10","15.00")
\$array=array("A","1","20","8.00")
\$array=array("A","2","20","14.00")
\$array=array("B","1","10","5.00")
\$array=array("B","2","10","9.00")
\$array=array("B","1","20","8.00")
\$array=array("B","2","20","14.00")
\$array=array("C","1","10","5.00")
\$array=array("C","1","20","8.00")

[A][5.00]
[A][9.00]
[A][15.00]
[A][8.00]
[A][14.00]
[B][5.00]
[B][9.00]
[B][8.00]
[B][14.00]
[C][5.00]
[C][8.00]

Now, this array holds quantities of a product (e.g. 1x10, 2x10, 4x10, 1x20, 2x20) and prices. Of course, the prices would be different, I simplified the example for EE though.

I want to be able to chose a quantity (1, 2, 4 or 6) and have all the results which have that quantity returned, or, if they don't exist, calculated.
Example:
number = 1
[A][5.00]
[A][8.00]
[B][5.00]
[B][8.00]
[C][5.00]
[C][8.00]
This one is very easy because all these results do exist in \$array, I can simply use array_filter or just use a foreach (\$array as \$x) loop and only keep those results where \$x == 1. I know how to do that.

number = 6 (LET'S CALL THIS ARRAY \$number6)
As you can see, there are no results in \$array that have a quantity of 6. They have to be calculated.
[A][22.50]
[A][42.00]
[B][27.00]
[B][42.00]
[C][30.00]
[C][48.00]
Now this wouldn't be very difficult either (simply take the 1 values and multiply by 6).
HOWEVER, since price discounts can apply, for each letter (A, B, C) the price of the highest quantity in the original \$array has to be divided by itself and then multiplied by 6.

Example:
Original \$array
[A][5.00]
[A][9.00]
[A][15.00] for A and 10, the highest quantity is 4, thus 15 / 4 * 6 = 22.50
[A][8.00]
[A][14.00] for A and 20, the highest quantity is 2, thus 14 / 2 * 6 = 42
[B][5.00]
[B][9.00] for B and 10, the highest quantity is 2, thus 9 / 2 * 6 = 27
[B][8.00]
[B][14.00] for B and 20, the highest quantity is 2, thus 14 / 2 * 6 = 42
[C][5.00] for C and 10, the highest quantity is 1, thus 5 / 1 * 6 = 30
[C][8.00] for C and 20, the highest quantity is 1, thus 8 / 1 * 6 = 48

This returns the array \$number6 (as above).

Thus, what has to be done is always the same:

Take the original \$array. Depending on the number \$n that is chosen (1, 2, 4 or 6), go and find the one row (subarray) with the highest quantity (field ) that is smaller than or equal to \$n for every possible combination of the fields  and  (i.e. A and 10, A and 20, B and 10, B and 20, C and 10, C and 20). Divide the price (field ) of this row/subarray by quantity (field ) and multiply by \$n. Then return a new array with the results.

Thank you for your help.

Cheers, Chris

PHP Last Comment
Lupi05

8/22/2022 - Mon
MMDeveloper