Json_encode更改我的查询顺序 [英] Json_encode changing the order of my query

查看:210
本文介绍了Json_encode更改我的查询顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按列排序的mysql查询.如果我只是运行php,它就可以正常工作.在我使用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?

查询如下:

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());
 };

因此,我想要并以纯PHP格式获取的输出是这样的:(ID = primary_key)

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

在我对数组进行json_encode并输出到客户端之后,我得到了:(ID = primary_key)

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

我希望这是有道理的.

推荐答案

简短的答案是:不要使用

Short answer is : don't use

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

建立阵列.改为使用以下语法构建一个基于0的实际数字索引数组:

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

另一种选择是,要保留当前结构,可以使用* sort系列函数(特别是 usort )在php中而不是SQL中对数组进行排序,就像这样(假设您的"order" 字段为数字,请参见 http://www.php.net/manual/zh-CN /function.usort.php (带有字符串类型字段的示例):

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;});

这篇关于Json_encode更改我的查询顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆