I am trying to store information about a game map in a MySQL database. To do this, I will have a VARCHAR field for each map containing an array of integers. This array of integers will contain maybe 1000 numbers corresponding to the id’s of different graphical elements stored in the database.
For example, it may contain a 2d array like this (a 3×3 cell map)
1,1,4
2,5,6
1,1,1
There would then be a table in my database like this
tiles
id | file | desc | other data //...
1 grass.png a grass tile
2 water.png a water tile
When a user queries the database for the map, I need to send the 2d array as well as the information about the elements. e.g. if the array contains the number 2, I need to return information saying that any cell with id 2 should be drawn as a water tile, file name water.png etc.
How is best to implement this efficiently? I don’t really want to have to go through the entire array in php, get the unique id values and query the database again for the information afterwards (seems inefficient to me).
I was thinking about having another field containing the unique ids in the format 4,1,2,5,6 that would be updated whenever the 2d array was altered. If this is a good idea, how can I query using it? something like this below doesn’t seem to work for me
SELECT * FROM tiles WHERE id IN ( SELECT unique_ids FROM mapInfo WHERE id = ..)
Basically, using comma delimited lists in column data is very inflexible. Anytime you think you should create a comma delimited list, you probably should create a new table and put each item in that list in a separate row then relate that new table back to the original table.
I would suggest you create a table called “cell” with the following columns:
Then you would query the 2d array with tile information like this:
If you wanted to have multiple “levels” or “maps” add a map_id column to your cell table so you could keep them separate. You should also add that column to the beginning of the primary key and you would query like this:
You might even want to keep a map table so you can store a name for each map, possibly the dimensions (100×100, 200×300, etc), etc.
Just some thoughts.