Reputation: 3
I have this piece of code that currently almost does what I need. It needs to select all records from a table and then format them ready for encoding to JSON. However, ONE record will have a "type" field set as "default". This record is placed first in the JSON file and formatted slightly different.
Currently this works prefectly if the record set to default is the last entry in the database table. But, if it isn't, then the formatting breaks when encoding to JSON.
Can anyone help suggest a fix that would force it to ignore where the default entry is, but retain the formatting?
// Get the data from the DB.
$query = 'SELECT type, headline, startDate, text, media, caption, credits FROM #__timeline_entries'.$table.'';
$db->setQuery($query);
// Load it and put it into an array
$list = $db->loadObjectList();
$len = count($list);
$data = array();
for ($i = 0; $i < $len; $i++) {
$temp = (array) $list[$i];
$temp["asset"] = array(
"media" => $temp["media"],
"credit" => $temp["credits"],
"caption" => $temp["caption"]
);
unset($temp["media"]);
unset($temp["credits"]);
unset($temp["caption"]);
if ($temp["type"] == "default") {
$data = $list[$i];
unset($list[$i]);
$list[$i] = $temp;
}
}
// Prep it for JSON
$data->date = &$list;
// Loop it once more!
$dataTwo->timeline = &$data;
// Encode the data to JSON.
$jsondata = json_encode($dataTwo);
This is part of a Joomla component, but it doesn't really use any of the Joomla framework beyond the database connection. I thought I'd mention it just in case it made any difference, though I don't see how.
Upvotes: 0
Views: 86
Reputation: 781350
Add an ORDER BY clause:
ORDER by (type = "default")
This will be 0 for all the records except the default, which is 1, so it will be put last.
Upvotes: 2
Reputation: 507
Add a WHERE clause to your MySQL statement:
$query = 'SELECT type, headline, startDate, text, media, caption, credits FROM #__timeline_entries'.$table.' WHERE type <> default';
Upvotes: 0