【问题标题】:Json_encode changing the order of my queryJson_encode 改变我的查询顺序
【发布时间】:2014-01-08 17:06:08
【问题描述】:

我有一个按列排序的 mysql 查询。如果我只运行 php,它工作正常。在我使用 json_encode 并将其发送给客户端后,顺序更改为主键。为什么会这样,有解决办法吗?

查询如下:

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)

  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)

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

我希望这是有道理的。

【问题讨论】:

  • 究竟在哪里发生了变化,你能澄清一下并举个例子吗?数据在哪一点发生变化?
  • 我以前也遇到过这个问题,在我的情况下,我最终不得不通过在原始数据旁边传递一个 order 数组在 Javascript 中对其进行重新排序

标签: php mysql pdo sql-order-by json


【解决方案1】:

如果您使用带数字的文字对象,客户端会自动对数组进行排序。 所以如果你省略了 id 你应该得到正确的内容。

替换

while ($row = $count->fetch()) {
    $id = array_shift($row);
    $myarray[$id] = $row;
}

//doing so you create this
json array=[
 0=undefined,
 1={order:5,id:1;location1},
 2={order:4,id:2;location2},
 3={order:3,id:3;location3},
 4={order:2,id:4;location4},
]
//error

while ($row = $count->fetch()) {
    $myarray[] = $row;
}

基本上你将你的文字对象转换成一个简单的数组。如果你开始删除一些图像,可能会导致几个错误。

那么您可能只需要 id 和位置

所以

SELECT id,location FROM ... ORDER BY order ASC

你有

[[1,location1],[2,location2]]

[{id:1,location:"location1"},{id:2,location:"location2"}]
  //0 wich is order 1        //1 wich is order 2

你的mysql查询创建的排序顺序是json数组索引。

【讨论】:

    【解决方案2】:

    简短的回答是:不要使用

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

    构建您的阵列。使用以下语法构建一个真正的基于 0 的数字索引数组:

    $myarray[] = $row;
    

    数组将按照项目的循环顺序构建,尽管记录结构略有不同(没有有意义的键)。

    作为替代方案,为了保留当前结构,您可以使用 *sort 系列函数(特别是 usort)在 php 中而不是 SQL 中对数组进行排序,就像这样(假设您的“顺序" 字段是数字,有关字符串类型字段的示例,请参见 http://www.php.net/manual/en/function.usort.php):

    while ($row = $count->fetch()) {
        $myarray[] = $row;
    }
    usort($myarray,function ($a, $b){return ($a > $b) ? 1 : -1;});
    

    【讨论】:

    • 谢谢。这很简单。
    猜你喜欢
    • 2018-01-14
    • 2019-04-20
    • 2014-01-21
    • 2017-11-18
    • 1970-01-01
    • 2015-02-23
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多