PHP Two-Dimensional Associative Array Implode
I'd like to store the following array in a single text field in a mySQL table:
$user_rating[0] = array('percent' => 'XXXXXXXXXXXXXXXXX',
'category' => 'Category 1',
'description' => 'XXXXXXXXXXXXXXXXX',
'link' => 'XXXXXXXXXXXXXXXXX',
'thumbnail' => 'XXXXXXXXXXXXXXXXX');
$user_rating[1] = array('percent' => 'XXXXXXXXXXXXXXXXX',
'category' => 'Category 2',
'description' => 'XXXXXXXXXXXXXXXXX',
'link' => 'XXXXXXXXXXXXXXXXX',
'thumbnail' => 'XXXXXXXXXXXXXXXXX');
$user_rating[2] = array('percent' => 'XXXXXXXXXXXXXXXXX',
'category' => 'Category 3',
'description' => 'XXXXXXXXXXXXXXXXX',
'link' => 'XXXXXXXXXXXXXXXXX',
'thumbnail' => 'XXXXXXXXXXXXXXXXX');
$user_rating[3] = array('percent' => 'XXXXXXXXXXXXXXXXX',
'category' => 'Category 4',
'description' => 'XXXXXXXXXXXXXXXXX',
'link' => 'XXXXXXXXXXXXXXXXX',
'thumbnail' => 'XXXXXXXXXXXXXXXXX');
$user_rating[4] = array('percent' => 'XXXXXXXXXXXXXXXXX',
'category' => 'Category 5',
'description' => 'XXXXXXXXXXXXXXXXX',
'link' => 'XXXXXXXXXXXXXXXXX',
'thumbnail' => 'XXXXXXXXXXXXXXXXX');
$user_rating[5] = array('percent' => 'XXXXXXXXXXXXXXXXX',
'category' => 'Category 6',
'description' => 'XXXXXXXXXXXXXXXXX',
'link' => 'XXXXXXXXXXXXXXXXX',
'thumbnail' => 'XXXXXXXXXXXXXXXXX');
$user_rating[6] = array('percent' => 'XXXXXXXXXXXXXXXXX',
'category' => 'Category 7',
'description' => 'XXXXXXXXXXXXXXXXX',
'link' => 'XXXXXXXXXXXXXXXXX',
'thumbnail'开发者_开发百科 => 'XXXXXXXXXXXXXXXXX');
I believe I need to implode the associative arrays as well to accomplish this but am having some trouble.
Any other/better array structure solutions are also welcomed.
Thanks
First, you don't need to specify ordered numeric keys, just write:
$user_rating[] = array();
Second, why would you want to store the entire array as a string? Why not just store each of its fields as s column? Is this not an option?
Third, you can store serialized arrays (or any data, for that matter) in the DB.
serialize($user_rating);
store_to_db();
...
$handler = unserialize(get_data_out());
If you want to store it as a straight up string, however, that's a bit more complicated. You would have to cycle through the array and append the keys and values individually.
You can use PHP's serialize
to convert the array to a single string. When you retrieve it from the database you can use unserialize
to convert it back to the array.
There is a better solution for sure.
Store this data as a separate records in a dedicated table.
That's what relational databases are for.
Have you considered JSON? It might be your best bet if you want to stick to a single field.
PHP - JavaScript Object Notation
edit: Or even better, read (and vote) for the comment below, because serialize
is a native function.
精彩评论