Here is my PHP script. What I wish to do is to sort the response array by a key. The key that I wish to sort the array by is a component of the row. To better clarify, say the row contained a string and an int type object. How can I sort the array using the int object as key? I have looked at ksort() and understand how to use it but I am unsure how to use it in the way that I am attempting to.
<?php
// array for JSON response
$response = array();
$host = "localhost"; //server
$db = "Test"; //database name
$user = "root"; //dabases user name
$pwd = "xxxxxxx"; //password
$link = mysqli_connect($host, $user, $pwd, $db);
$result = mysqli_query($link, "SELECT * FROM Table");
// check for empty result
if (mysqli_num_rows($result) > 0)
{
$response["stuff"] = array();
$event = "";
while ($row = mysqli_fetch_array($result)) {
$event = $row;
$response[] = event;
}
//Here I wish to sort the array by the int object as key.
$response["success"] = 1;
echo json_encode($response);
}
?>
The comments above might answer this specific requirement, but I would like to also describe how to sort a PHP array like the question poster wants to:
The method of choice is not ksort()
(sort by key), butusort (&$array, $value_compare_func)
(sort by user-defined callback):
usort($response['stuff'], function($a, $b) {
return $a['integer'] - $b['integer'];
});
Where the closure function is a simple integer comparison using array members as operands (with key integer
in this example).
When comparing other types of values, the comparison function should be adapted to meet the requirements of usort()
. E.g. for strings, one would use strcmp()
.