4

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 :)

Adam Kiss
  • 11,811
  • 9
  • 48
  • 81

4 Answers4

7

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

Mchl
  • 61,444
  • 9
  • 118
  • 120
  • 1
    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 – Boris Delormas Jul 27 '10 at 07:58
  • A good SO ressource anyway : http://stackoverflow.com/questions/804045/preferred-method-to-store-php-arrays-json-encode-vs-serialize/804053#804053 – Boris Delormas Jul 27 '10 at 08:01
  • Doesn't have serialize problems with UTF? – Adam Kiss Jul 27 '10 at 09:36
  • @Kaaviar: until somebody comes with better question, I thank you, this seems like the best answer (that I somehow haven't seen) – Adam Kiss Jul 27 '10 at 09:44
3

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
  • 38,379
  • 25
  • 128
  • 201
2

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.

dockeryZ
  • 3,981
  • 1
  • 20
  • 28
  • mostly metadata for content: various directives how to show it, author, date and other information I DO NOT NEED to fullsearch on. – Adam Kiss Jul 27 '10 at 09:34
1

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
  • 209,507
  • 32
  • 346
  • 385
  • 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 Jul 27 '10 at 09:35