Skip to content
Advertisement

Matching IDs in 2 different foreach loops in PHP (CodeIgniter)

So basically, what I’m trying to achieve is calculating the tax percentage on each food category.

Lets suppose category number 5 having the tax percentage of 8%.

So based on simple formula to calculate tax on each item is:

ITEM COST * TAX % / 100 = Tax Amount

So I have 2 arrays

ARRAY 1:

JavaScript

ARRAY 2:

JavaScript

table food-category here

Some sub functions used inside get_per_tax_amount()

JavaScript

Example:

JavaScript

output is:

JavaScript

I don’t know why I am getting this output.

So my problem is, how do I match the CATEGORY-ID using foreach loop and get each item tax amount?

Advertisement

Answer

You can achieve a relatively straightforward algorithm if you restructure your input arrays. Currently, you have ungrouped data and some unnecessary levels. This adds complexity to your function that is supposed to calculate tax amounts. If we redesign the arrays to a more fitting format, we can simplify the function.

The array that holds tax percentage values per category can be a simple one-dimensional array (because here you logically do not need duplicate values), like so:

JavaScript

The one that holds item prices and their categories could be made into an array where top level keys are category ids and their values are subarrays of all item prices in that category, like so:

JavaScript

With arrays neatly organized, we can now reduce the calculation function to this:

JavaScript

How it works:

  • We don’t need to loop the percentage array at all. We will only use it for reference.
  • The outer loop iterates over the units and the inner loop iterates over all the unit prices in the category.
  • For every price, we simply access the index in the percentage array equal to the current category key of the outer loop and do the calculation. You might want to add a check if that array key exists in the percentage array (this code assumes it will exist) and then handle that case however would be best for your application (throw exception, return empty array…).

Now, I haven’t tested this final bit, but to achieve these array structures, I believe you only need to change the following:

  1. In the get_category_tax_value() function, change this:
JavaScript

to this:

JavaScript

to remove the extra dimension.

  1. In the get_per_menu_price() function, change this:
JavaScript

to this:

JavaScript

to add prices in a subarray.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement