我正在创建一个应用程序,将json提要解析为listactivity。我读到在列表视图的底部添加了新项目,我的应用程序就是这样。我正试图通过按id降序对json的输出进行排序来解决这个问题。不知道这是否能解决我的问题,或者我需要在我的java代码中纠正它。我问题的第一部分是,更改数据库输出的顺序会更改提要在应用程序中的显示顺序吗?如果是这样的话,我已经尝试通过以下示例修改我的php脚本:http://php.net/manual/en/function.usort.php但顺序不变。第二部分,我在下面的php脚本中做错了什么?
<?php
require("config.inc.php");
$query_params=null;
//initial query
$query = "Select * FROM feeds";
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
if ($rows) {
$response["feed"] = array();
foreach ($rows as $row) {
$post = array();
$post["id"] = $row["id"];
$post["name"] = $row["name"];
$post["status"] = $row["status"];
//update our repsonse JSON data
array_push($response["feed"], $post);
}
function cmp($a, $b)
{
if ($a->id == $b->id) {
return 0;
}
return ($a->id > $b->id) ? -1 : 1;
}
$a = array();
usort($a, "cmp");
// echoing JSON response
echo json_encode($response, JSON_NUMERIC_CHECK);
} else {
$response["success"] = 0;
$response["message"] = "No Post Available!";
die(json_encode($response));
}
?>
看起来您在一个空数组上调用usort,而不是实际要排序的数据。
代替
$a = array();
usort($a, "cmp");
尝试
$a = $response['feed'];
usort($a, "cmp");
$response['feed'] = $a;
Blackbelt说得对,从技术上讲,你不能对JSON数组进行排序,至少要对一个有顺序索引的数组进行排序(这会导致根本没有索引)。然而,在实践中,当您在客户端迭代得到的对象时,它将按照定义的顺序,因此在服务器端对其进行排序应该不会引起任何问题。