While fixing a bug in a legacy app, I ended up leveraging a PostgreSQL array in a select query, which ends up with each result row of the fetched array being something like:
[0] => array(
'foo' => '{12345,"some text","other text"}',
'bar' => 'different field',
'fubar' => 'yet another field'
)
To get each of the 3 parts of the foo
element into their own fields to make it easy for the view to display it, I did something like:
foreach($result as $ix => $data) {
if(!empty($data['foo'])) {
$fields = json_decode('['.trim($data['foo'], '{}').']', true);
$result[$ix]['fld1'] = $fields[0];
$result[$ix]['fld2'] = $fields[1];
$result[$ix]['fld3'] = $fields[2];
}
else {
$result[$ix]['fld1'] = '';
$result[$ix]['fld2'] = '';
$result[$ix]['fld3'] = '';
}
}
I'm pretty sure there must be a cleaner way to do that using array_map()
or such, plus the json_decode(...)
bit seems pretty kludgy, so just wondered if anyone has any suggestions for better ways, in terms of efficiency and maintainability? (It works fine, and it's not a high-demand app requiring lightning response time...but I'm not happy with it as it is. 🙂 )