Skip to content
Advertisement

Find which array an item is in given multiple arrays and item only exists in one in PHP/SQL

I have an ecommerce website and I have it set up that countries are split into different zones for shipping costs.

I have 8 zones, these are all arrays of country codes, there can be no duplicates in the arrays or items can’t exist in multiple arrays.

I then want to calculate the shipping costs for a given country. So I basically want to find out which zone the country is in.

What I do at the moment is I query my shipping zones by the items supplier to get all of the arrays and then do an if(in_array()) on each of these like so:

There has to be a better way of doing this, I thought it might be easier to do it in the initial SQL query but the actual arrays are serialized in the DB.

Advertisement

Answer

From your question it looks like the schema for shipping_zones looks something like this:

It sounds like there are 2 things you’d like to accomplish here:

  1. Maintain data integrity (“there can be no duplicates in the arrays or items can’t exist in multiple arrays”)
  2. Make your code simpler/more maintainable (“There has to be a better way of doing this…”)

Assuming you have full control over the application and the database, I would recommend changing your database schema so that your RDBMS can do more work for you. I suggest a schema that looks more like this:

This way you can’t accidentally put a country in multiple zones for a given supplier, and your task of getting the correct code for the given supplier becomes as simple as the following query:

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