0

I'm creating an app that parses json feeds into a listactivity. I've read that new items are added at the bottom of a listview and this is the case in my app. I'm trying to remedy this by sorting the output of my json by id in descending order. Don't know if this will fix my problem or I need to remedy it in my java code. Part one of my question is, will changing the order of output from the database change the order in which the feeds are displayed in the app? If so, I've tried to modify my php script by following the examples on http://php.net/manual/en/function.usort.php but the order doesn't change. Part two, What am I doing wrong in the following php script?

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

?>
Macharia
  • 55
  • 2
  • 11
  • you can't sort a json object. Once you parse the json client you can sort the collection result of the parsing – Blackbelt Mar 18 '15 at 16:30

1 Answers1

0

Looks like you are calling usort on an empty array, instead of the data that you actually want to sort.

Instead of

$a = array();
usort($a, "cmp");

Try

$a = $response['feed'];
usort($a, "cmp");
$response['feed'] = $a;

Blackbelt is right that you can't technically sort a JSON array, at least one with sequential indexes (which results in no indexes at all). In practice, though, when you iterate through the resulting object on the client side, it will be in the order it was defined, so sorting it server-side should not raise any issues.

rjdown
  • 9,162
  • 3
  • 32
  • 45
  • @Blackbelt and rj, by 'you can't technically sort a json array', does this mean that what I'm attempting is futile? Most of what I've learned about json and php and really programming in general is from online tutorials so pardon my naivety. Also, I get the following error `
    Fatal error: Function name must be a string in D:\Program Files\XAMPP\htdocs....` when I implement the above change. I'm tesing with xampp before I alter the online script.
    – Macharia Mar 18 '15 at 18:18
  • What you're doing is fine, there is just the possibility that when the JSON is converted to an object/array on the client side, it may not necessarily keep the order. Depends a lot on the client. Safer to sort on the client side just to be sure, if you prefer. Ref the fatal error, unsure what's happening there. Code seems fine. What line is it saying has the issue? – rjdown Mar 18 '15 at 18:33
  • line 48 which is `$a = $response('feed');` – Macharia Mar 18 '15 at 19:32
  • Ah, they should be square brackets as per my example. `$a = $response['feed'];` – rjdown Mar 18 '15 at 20:02
  • I also think you'll get a "trying to get property of a non-object" error from within your cmp function. If so, change everything that looks like `$a->id` to e.g. `$a['id']` – rjdown Mar 18 '15 at 20:13
  • Changed the brackets, it threw the error you anticipated it would, changed to `$a["id"]` and now the output is ok but still unsorted – Macharia Mar 18 '15 at 21:56
  • Seems to work ok here http://sandbox.onlinephpfunctions.com/code/d4c46cbd1dd929b8864cc9a7c73674f99270c166 (added some random data at the top) – rjdown Mar 18 '15 at 22:11
  • 1
    Thank you so so so much!! It works, had `$response["feed"];` instead of `$response["feed"] = $a;` Thank you, again! – Macharia Mar 18 '15 at 22:28