views:

33

answers:

4

Hi,

I'm thinking of storing data from a form as a string, each answer separated by a pipe. The problem I have is that some answers may come in the form of multiple items. We store the radio button selection along with their corresponding answers e.g.

Question 1 - 1 Answer [A1]
Question 2 - Radio button selected [A2] + 3 form fields
Question 3 - 1 Answer [A3]

So I was thinking of storing the data like:

$str = A1|A2[x,x,x]|A3

The reason I chose to enclose multiple selections in brackets is in order to have it relate to the question.

I think my solution will work but when I come to read the values from the database I'll use Php's explode() to get the values into an array.

E.g. explode("|",$str);

Will give:

array(0=>A1, 1=>A2[x,x,x],2=>A3);

Before developing this, what would be the best way of getting the content of [x,x,x] and separating it from array[1]?

Any suggestion will be much appreciated.

Thanks

A: 

Your approach doesn't provide any benefit and it introduces an unnecessary complexity. Why don't you just use a relational database and store each piece of data a in a separate table row? If you don't have access to MySQL or a similar DBMS, you can always use SQLite.

Álvaro G. Vicario
It would be very complicated with the setup we currently use.
A: 

I think you need to take a look at serialize and unserialize.

Htbaa
A: 

Alternatively, rather than having your answers as a string then trying to turn them to an array you could start with them in an array then if you need turn them into a string, so you could have:

$array = array('A1',array(x,x,x),'A3');

Then if you do need it as a string you can call:

$str = serialize($array);

That way, you get a similar method of access to your solution after you have exploded the string, only you don't have to deal with trying to split the A2[1,2,3] string further as you can just check if it's an array instead.

Mike
This sounds like a good solution. The only reason for a string is for storage in our existing settings DB setup. So I can call unserialize when calling the string from the database in order to access it as an array?Storing in DB -> serialize($array);Reading from DB -> unserialize($array);
Yes indeed. That's all there is to it.
Htbaa
A: 

You could also store the information as an associative array encoded into json with json_encode() function. Then when you fetch data from the database, you would just do:

$arr = json_decode($value);

http://php.net/manual/en/function.json-encode.php

Richard Knop
Unless you need to communicate to some other (remote) application you're better off using un/serialize.
Htbaa
True. But it doesn't make much difference. In both cases you can decode the string with single function. Personally, I like json format more.
Richard Knop