I have a large multidimensional array that I would like to store into a MySQL database.
Below is an example of the array in question:
Array
(
[user1] =>
[name] => abc
...
[address] => xyz
...
...
[user2] =>
[name] => abc
...
[address] => xyz
}
The array values and database table columns all match (apart from the rowid in the database). I have seen various methods of doing something similar, but haven't found a way that works in this solution.
Many thanks :)
Update
Updated the array structure to give a clearer idea whats in the array itself.
In the end I took the time to use a for loop and achieve the following:
for ($i = 0; $i < 25; $i++)
{
$name = $parts[$i][0];
$address = $parts[$i][22];
// Run SQL query using the variable values rather than the array values.
}
I'm sure there is a more sophisticated way of achieving this, but this worked for now!
Thanks all.
Usually when you've got nested data like this, it makes sense to have two tables.. one for parent and one for child, in order to most efficiently access the data. The parent table would have "Parent ID" and whatever parent level data, and the child table would have "Child ID", a "Parent ID" foreign key, and child data (in your example, the three character string).
Have you tried json_encode? You can turn your array into a string, store it and then use json_decode to turn it back.
If you are needing to store the array itself, use serialize() and unserialize() to store the array as a string within the database. Much better than the json option Dutchie mentioned previously since json can have issues with multidimensional arrays.
Or are you wanting to store the values in the associated records in the db?
If you're going to be storing arbitrarily deeply nested arrays, then either json_encode()
/json_decode()
or serialize()
/unserialize()
would be your best bets. The only issue is you'll be unable to query the data intuitively.
As already mentioned, modeling your tables in accordance would be optimal.
make a uni-dimensional array with serialized elements. You will insert one row only and each column will contain serialized arrays