Say if we had:
tbl `posts`
id | post_type | post_id | post_key | post_value | Locale
------------------------------------------------------------------------------
1 | news | 1 | title | The climate in Mongolia | pl_pl
2 | news | 1 | content | Mongolia has strange weather... | pl_pl
3 | news | 1 | date | 2015-9-24 | pl_pl
In order to get data for a post I would
SELECT post_key, post_value
FROM posts
WHERE post_id = 1 && post_type = 'news'
AND locale = 'pl_pl'
Then loop through the result set and mysqli_fetch_assoc() each row to give me an associative array with field names as the array keys;
$row['post_key'] == 'title'; $row['post_value'] == 'The climate in Mongolia';
$row['post_key'] == 'content'; $row['post_value'] == 'Mongolia has strange weather...';
What I would like is the actual values of post_key
to be the array keys, keeping the value as post_value
. So:
$row['title'] == 'The climate in Mongolia';
$row['content'] == 'Mongolia has strange weather...';
Yes I could format it like this with php and another loop, like:
$data = [];
foreach($rows as $r) {
$data[$r['post_key']] = $r['post_value'];
}
But I want to know if there is some mysql magic that could save the additional processing required in PHP?
Further info about this app: As Gal rightly pointed out, it seems strange that I wouldn't just use the field names as per the post_key's / conventional table design. But this is a translations table and I am exploring the possibility of having one table to cater for translations of many other content tables, and that I can use for new content types without too much faffing around with creating multiple additional tables and maintaining new fields across them. Reasons that I am not to worried about performance at this stage: 1. being the only developer on this startup project and where decisions are being made on the fly, I believe this will save time and tick all boxes for now. 2, number of entries will be low compared to a couple of years time, where we would have time then to look a solution to any performance issue that arises.