I have a 5 level multidimensional array. The number of keys in the array fluctuates but I need to store it in a database so I can access it with PHP later on. Are there any easy ways to do this?
My idea was to convert the array into a single string using several different delimiters like #* and %* and then using a series of explode() to convert the data back into an array when I need it.
I haven't written any code at this point because I'm hoping there will be a better way to do this. But I do have a potential solution which I tried to outline below:
here's an overview of my array:
n=button number
i=item number
btn[n][0] = button name
btn[n][1] = button desc
btn[n][2] = success or not (Y or N)
btn[n][3] = array containing item info
btn[n][3][i][0] = item intput type (Default/Preset/UserTxt/UserDD)
btn[n][3][i][1] = array containing item value - if more than one index then display as drop down
Here's a run-down of the delimiters I was going to use:
#*Button Title //button title
&*val1=*usr1234 //items and values
&*val2=*FROM_USER(_TEXT_$*name:) //if an items value contains "FROM_USER" then extract the data between the perenthesis
&*val3=*FROM_USER(_TEXT_$*Time:) //if the datatype contains _TEXT_ then explode AGAIN by $* and just display a textfield with the title
&*val4=*FROM_USER($*name1#*value1$*name2#*value2) //else explode AGAIN by $* for a list of name value pairs which represent a drop box - name2#*value2
//sample string - a single button
#*Button Title%*val1=*usr1234&*val2=*FROM_USER(_TEXT_$*name:)&*val3=*FROM_USER(_TEXT_$*date:)&*val4=*FROM_USER($*name1#*value1$*name2#*value2)
In summary, I am seeking some ideas of how to store a multidimensional array in a single database table.
What you want is a data serialization method. Don't invent your own, there are plenty already out there. The most obvious candidates are JSON (json_encode) or the PHP specific serialize. XML is also an option, especially if your database may support it natively to some degree.
Have a look at serialize or json_encode
The best decision for you is json_encode.
It has some advantages for json_encode beside serialize for storing in db.
taking smaller size
if you
must modify data manually in db there will be some problems with serialize, because this format stores size of values that has been serialized and modifying this values you must count and modify this params.
SQL (whether mySQL or any other variant) does not support array data types.
The way you are supposed to deal with this kind of data in SQL is to store it across multiple tables.
So in this example, you'd have one table that contains buttonID, buttonName, buttonSuccess, etc fields, and another table that contains buttonInputType and buttonInputValue fields, as well as buttonID to link back to the parent table.
That would be the recommended "relational" way of doing things. The point of doing it this way is that it makes it easier to query the data back out of the DB when the time comes.
There are other options though.
One option would be to use mySQL's enum feature. Since you've got a fixed set of values available for the input type, you could use an enum field for it, which could save you from needing to have an extra table for that.
Another option, of course, is what everyone else has suggested, and simply serialise the data using json_encode() or similar, and store it all in a big text field.
If the data is going to be used as a simple block of data, without any need to ever run a query to examine parts of it, then this can sometimes be the simplest solution. It's not something a database expert would want to see, but from a pragmatic angle, if it does the job then feel free to use it.
However, it's important to be aware of the limitations. By using a serialised solution, you're basically saying "this data doesn't need to be managed in any way at all, so I can't be bothered to do proper database design for it.". And that's fine, as long as you don't need to manage it or search for values within it. If you do, you need to think harder about your DB design, and be wary of taking the 'easy' option.
Related
I have some questions about handling with array concerning storing in mysql.
I stored an array (of numbers) in my mysql database as text Like: COLUMN_ARRAY: [2,3,4,5,6,7]
( including [ and ] )
My first question: is this a good method or can I work with that for my further steps? or are there any other better methods for storing array in sql column?
My second question: how could it be possible to pick every single element, or go throu all elements in the array with php?
because I want to make a query like if COLUMN_ARRAY includes the number 3 then do blablabla...
maybe you can give me some hint, idea, link or tutorial :)
EDIT:
Ok I did some change and changed everything to something like that:
How to store arrays in MySQL?
the only problem is now: how can I handle with an array (like [1,2,3]) in php - to handle with every single element in that?
Long time reader first time questioner...
I'm attempting to use Drupal to create a set of variables, not the issue, it's all in place to set them and simple for the future operator to edit.
I then need to grab these values in php, still on the site but outside of Drupal to some extent. Again, although I'm a bit of a lightweight on PHP, I can get what I need. However drupal stores the data all in one "cell" (apologies, I've searched for what I'm after but I think my vocabulary is lacking to get the right result!). Here's an example of how it is stored:
a:3:{i:0;a:3:{s:5:"value";s:2:"38";s:5:"label";s:11:"Cost Per
M2";s:6:"weight";s:1:"0";}i:1;a:3:{s:5:"value";s:1:"7";s:5:"label";s:13:"Arch
Top
Cost";s:6:"weight";s:1:"1";}i:2;a:3:{s:5:"value";s:1:"5";s:5:"label";s:13:"Flat
Top Cost";s:6:"weight";s:1:"2";}}
So I can happily return the whole contents as above, but I haven't the slightest how to refine it down to a specific reference. I can work out the data is contained between certain sets of brackets so, one ref is:
{s:5:"value";s:2:"38";s:5:"label";s:11:"Cost Per M2";s:6:"weight";s:1:"0";}
What I really need is the "38" in the example, as this is a cost that a 2nd system uses a number of to calculate a final cost.
I hope this makes sense?
The value is serialised (see http://php.net/manual/en/function.serialize.php). What you want to do is unserialize it (see http://www.php.net/manual/en/function.unserialize.php). So it would be:
$deserializedValues = unserialize($values).
After that you can call the variables by doing:
$deserializedValues['value'] (if an array)
$deserializedValues->value (if an object)
Drupal returns JSON. The cleanest way to handle this would be to use PHP's json_decode() function:
http://php.net/manual/en/function.json-decode.php
To give some background, I'm creating a web app using mostly jQuery. I scrape a number of values from a page on another domain; 3 arrays of integers and a date in string format. These values are then displayed on my page. Each of these arrays has 7 numbers.
It makes sense to me to store each array as a single entry in my MySQL database. My original idea was to store the values of each array as a JSON object and insert that into my entry in the DB from reading around SO this doesn't seem like the approach to take. I don't envisage having any need to sort the values at any stage in the future. I will just need the value of each integer and don't need to know how each integer in each array relates to one another.
Can someone point me in the right direction regarding the storing and retrieval of these values?
Usually arrays are kind of iffy to handle. In most cases arrays are values that I need to process later in the front end for the user with javascript (can't think of another use anyway). Therefore what I usually do is store them as text by using
$array = array('one', 'two', 'three');
$textToSaveinDB = implode(',', $array);
When I retrieve this you would just use the other way around
$textFromDB = "one,two,three";
$array = explode(textFromDB, ',')
Afterwards you can do whatever you need to do with the array. For example use JSON_encode() and send it to the user via ajax.
Maybe serialize() and unserialize() would help you. But I won't suggest this as the best approach.
I have a list of strings (names) which I would like to match to the database containing the same or variances of these names.
For each of the strings I want to match I can query the database, but this doesn’t seems to be efficient since the database is a fix set of names.
I was wondering if it was possible to have this match being done within PHP. I can use the levenshtein function in PHP, but I was wondering if there is anything more efficient.
The example I want to get to. On the left are all the strings I want to see if I have this in the database (or a small variance). Next to each I would like to have a pull down list containing the options that match closely.
String 1 – pull down
String 2 – pull down
String 3 – pull down
What is the best approach to this? I have about 500-1000 strings for which I would like to get a suggestion/pull down menu.
With kind regards
Ralf
Perhaps have a look at MySQL's full text search feature. I found this article on DevZone: http://devzone.zend.com/26/using-mysql-full-text-searching/
If you want to do it client-side, jQuery UI Autocomplete is what you want. Not only that is very easy to configure it for your needs, but you can do it with only 1 query that would get all the strings and save it into a local list, the jQuery Autocomplete data source.
You can then register an onkeyup event for an input and the jQuery plugin will query the existing cached datasource(no more pressure for your server).
Check it out:
http://jqueryui.com/autocomplete/
O.K. so I'm pretty clever - I've made a library for keeping a bunch of WP themes that are all set up to my needs so when I put out a new site I can just create the new blog in a few minutes.
As a holder for the new domain everything in the sql file that has the old domain in it I replace with [token].
Everything was working fine right up to the point where I made one with a child theme that apparently serialized data before entering it into the database. End up with stuff like this:
Theme','a:8:{s:12:\"header_image\";s:92:\"http://[token]wp-content/uploads/2011/05/494-Caring-for-fruit-trees-PLR.jpg\";s:16:\"background_image
So I dig into serialization and it turnss out that s:92 bit for example is the number of characters in that value. Since i'm changing [token] it changes and breaks.
Up till now I did all my changes to the sql file and didn't edit the database other than to populate it with the sql file - but I'm at a loss on how to deal with the data in the serial array.
Any ideas?
Easiest way would be to grab that data and use the unserialize() function, like
$arr = unserialize($data);
Then edit the data that way. When you're done, re-serialize it with serialize(), and store it back. You may have to to do a print_r() on the unserialized data to see how it's stored to see what you need to edit.
If you do the changes directly from the serialized data, you'll have to get the length of the current substring, make the change, then get the new length and splice that back into the serialized data, which is way more complicated than it needs to be.