I have a set of data in DB and I am sending it to my Android App using an API function.
I have written this in PHP.
I want to sort JSON array in alphabetical order and then send it in JSON array format.
Here is the code I have, I am not sure how or where to sort this out?
$response["categorydetails"] = array();
while ($categoryrow = mysqli_fetch_array($categorylist))
{
// temp user array
$categorydetail = array();
$categorydetail["sno"] = $categoryrow["sno"];
$categorydetail["category"] = $categoryrow["category"];
// push single product into final response array
array_push($response["categorydetails"], $categorydetail);
}
$response["success"] = 1;
$response["message"] = "Login Successful";
echo json_encode($response);
Can someone help me figure this out?
Thanks!
CodePudding user response:
Since you're getting the data from a database, it would make most sense to sort the data using an ORDER BY
clause in the SQL query. This will be much more efficient than trying to sort it in PHP.
I don't know your real query or table name, but this is the general idea:
SELECT * FROM someTable ORDER BY someColumn
You didn't say which column you want to sort by, but I'd guess it's the category
? In that case, ORDER BY category
would be what you need to add to your SQL.
Documentation: MySQL Reference Manual - Sorting Rows
CodePudding user response:
You've to alter the SQL query to set "ORDER BY" specific column name, instead of trying to change in the PHP 'while loop' code itself. Please share your SQL code as well, which might help us answering you better.