dongzu3511 2013-12-19 23:03
浏览 457
已采纳

Json_encode改变了我的查询顺序

I have a mysql query that orders by a column. It works fine if I just run the php. After I use json_encode and send it to the client, the order is changed to the primary key. Why does it do this and is there a solution?

Query looks like:

try{
    $dbh = new PDO('mysql:host=localhost;dbname=Batik', 'root', 'root');
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
    $_SESSION['table'] = $_SESSION['category'] = $table = $_GET['button'];
    $count = $dbh->query("SELECT * FROM $table ORDER BY `order` ASC");
    $count->setFetchMode(PDO::FETCH_ASSOC);
    $myarray = array();
    while ($row = $count->fetch()) {
        $id = array_shift($row);
        $myarray[$id] = $row;
    }
    print json_encode($myarray);
}  catch (PDOException $exception) {
    echo "There was an error uploading your information, please contact James for assistance. "; 
    error_log($exception->getMessage());
 };

So, the output I want and get in plain php is like this: (ID = primary_key)

  Order:     ID:      Location:
  1             4         foto1.jpg
  2             5         foto3.jpg
  3             3         foto2.jpg
  4             2          foto4.jpg
  5             1          foto5.jpg

After I json_encode the array and output to client, I get this: (ID = primary_key)

  Order:     ID:       Location:
  5             1          foto5.jpg
  4             2          foto4.jpg
  3             3          foto2.jpg
  1             4          foto1.jpg
  2             5          foto3.jpg

I hope this makes sense.

  • 写回答

2条回答 默认 最新

  • dousi1097 2013-12-19 23:14
    关注

    Short answer is : don't use

    $id = array_shift($row);
    $myarray[$id] = $row;
    

    to build your array. Build a real 0-based numerically indexed array instead with this syntax :

    $myarray[] = $row;
    

    and the array will be built with the items in the order they are looped over, although with a slightly different record structure (no meaningful keys).

    As an alternative, to preserve your current structure, you could order the array in php instead of SQL with the *sort family of functions (usort in particular), like so (assuming your "order" field is numeric, see http://www.php.net/manual/en/function.usort.php for an example with a string-type field) :

    while ($row = $count->fetch()) {
        $myarray[] = $row;
    }
    usort($myarray,function ($a, $b){return ($a > $b) ? 1 : -1;});
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站