Reputation: 3288
I have a fairly simple (at least I thought simple) task I'm trying to achieve but for the life of me I can't think of the best way of doing it in php.
Note I'm trying to avoid using nested multi-dimensional arrays.
What I want to do is a simple 2 axis reference table which I can query/look up against.
0 | 1 | 2 | 3 | 4 | 5
0 5 0 0 0 0 0
-
1 0 2 0 1 0 0
-
2 0 0 0 7 0 1
-
3 1 2 4 10 1 0
-
4 0 0 0 0 0 0
-
5 0 3 4 0 1 0
Then I want to query it so lookup_table(3,3) would return 10. I also need to update the values in the table so like add_lookup_table(3,3,1) would change location 3,3 to 11 or some variation of.
So far I know I can achieve it with multidim arrays however want to avoid this because its just going to be a pain in the ass getting and setting each time. I thought about a list() but php's lists aren't really lists so that goes out the window.
What I'm after is suggestions/recommendations for a better way of doing this.
Upvotes: 0
Views: 37
Reputation: 18568
you can just use a single array like so
$array = array(
5, 0, 0, 0, 0, 0,
0, 2, 0, 1, 0 , 0
..etc...
);
then each key is just $array[$row * 6 + $column]
so $array[3*6 + 3]
or define your array as something like
$array["3.3"] = 10;
both of the above are BAD ways to do it when a multidimensional array exists and is well suited for the task.
you list the reason you dont want to use it as "getting and setting each time" - what ever the solution, you will have to get and set to populate it.
The real solution here seems to be the one you wish to avoid
you MAY want to check
http://php.net/manual/en/spl.datastructures.php
That has extra structures
Upvotes: 1