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条)

报告相同问题?

悬赏问题

  • ¥15 FIR滤波器算法设计与实现(利用库函数firdec()
  • ¥15 利用单片机产生正弦信号,来测量差分放大电路放大倍数和共模放大倍数的思路和仿真
  • ¥60 关于mavlink的论文咨询
  • ¥66 定制开发肯德基自动化网站下单软件
  • ¥15 中科院研发的TextMind(文心)
  • ¥20 vscode虚拟环境依赖包未安装
  • ¥15 odoo17关于owl开发js代码问题
  • ¥15 光纤中多普勒频移公式的推导
  • ¥15 怎么制作一个人脸识别门禁系统
  • ¥20 大华dss监控平台网络关闭登不进去