views:

57

answers:

4

Hello,

I'd like to store associative array containg mostly strings and integers as values in db.

I was thinking:

  • implode/explode - need to find delimiter, which won't be in values - since it's almost user generated, not safe
  • XML - feels to heavy for the job (creating/reading values)
  • json - if i need only to work with json_decode/json_encode, seems perfect

What do you think?

Please, do not forward me to other questions like this on SO, I've read most of them and I'm still not sure :)

+6  A: 

I think serialize: http://php.net/manual/en/function.serialize.php

Mchl
Might be one of the best solution even if JSON will store less data I guess. Take a look here too : http://www.php.net/manual/en/function.json-encode.php
Kaaviar
A good SO ressource anyway : http://stackoverflow.com/questions/804045/preferred-method-to-store-php-arrays-json-encode-vs-serialize/804053#804053
Kaaviar
Doesn't have serialize problems with UTF?
Adam Kiss
@Kaaviar: until somebody comes with better question, I thank you, this seems like the best answer (that I somehow haven't seen)
Adam Kiss
@Adam Kiss : be my guest !
Kaaviar
+2  A: 

It really all depends on the way in which you want to retrieve this data once you DO get it in the database. Sure you could serialize an array and put it in your field, but what if you want to perform queries with the data in that array; you'd have to pull the serialized array out, perform PHP functions, and then do your query.

You need to explain what it is you want to achieve with this associative array data.

Zane Edward Dockery
mostly metadata for content: various directives how to show it, author, date and other information I DO NOT NEED to fullsearch on.
Adam Kiss
+1  A: 

You could either serialize() the array, or json_encode() it when writing to the database, and json_decode() when fetching from the database.

Martin Bean
A: 

There's also the option of creating a table with key and value columns, and storing each array element individually in that table. It might seem excessive, but could prove useful depending on what you want to do with the data

Mark Baker
I don't want to do that, because every new version of content saves as different "page" in db, and if every page has 10+ pairs, doing diff or other operations on content with more revisions results in... either mess or bazillion db operations.
Adam Kiss