0

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!

1
  • By which column you want to sort? Commented Oct 28, 2021 at 6:56

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.