dqvzfp6468 2012-09-30 16:39
浏览 38
已采纳

在php中忽略mysql记录的顺序

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.

  • 写回答

2条回答 默认 最新

  • doushu5805 2012-09-30 17:29
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计