我有2个mysql查询,一个用于获取所有朋友,另一个用于获取每个朋友的详细信息和点数总和。
$get_my_friends_query = mysqli_query($GLOBALS['connect'], "SELECT friend_user_id FROM tbl_friend_link WHERE tbl_friend_link.your_user_id = 1");
while($get_my_friends_result = mysqli_fetch_assoc($get_my_friends_query))
{
$get_friend_user_details_query = mysqli_query($GLOBALS['connect'], "SELECT tbl_registered_user.user_id, tbl_registered_user.first_name, tbl_registered_user.last_name, tbl_registered_user.profile_name, SUM(tbl_point.amount) FROM tbl_registered_user JOIN tbl_point ON tbl_registered_user.user_id = tbl_point.user_id WHERE tbl_registered_user.status = 1 AND tbl_registered_user.user_id = '" . $get_my_friends_result['friend_user_id'] ."' GROUP BY tbl_registered_user.user_id ORDER BY SUM(tbl_point.amount)");
$get_friend_user_details_result = mysqli_fetch_assoc($get_friend_user_details_query);
$result = array(
"done" => "true",
"name" => $get_friend_user_details_result['first_name'] . " " . $get_friend_user_details_result['last_name'],
"profile_name" => $get_friend_user_details_result['profile_name'],
"userID" => $get_friend_user_details_result['user_id'],
"points" => $get_friend_user_details_result['SUM(tbl_point.amount)'],
"number_friends" => mysqli_num_rows($get_my_friends_query),
"error_message" => ""
);
$row_array[] = $result;
}
echo json_encode($row_array);
我正在使用第一个查询,因为我希望显示结果,无论它们是否有任何点。我想根据点的总和对结果进行排序,但是在第二个查询中检索信息但是我找不到关于如何在$ row_array上使用usort的合适解释。
答案 0 :(得分:1)
我得到了以下内容:
function sorter($key){
return function ($a, $b) use ($key) {
return $a[$key] - $b[$key];
};
}
usort($row_array, sorter('points'));
var_dump($row_array);
答案 1 :(得分:0)
usort($row_array, function($a, $b)
{
return ($a['points']<$b['points']) ? 1 : -1;
});
答案 2 :(得分:0)
要“显示它们是否有任何点”,你应该查看外连接。 Sams Teach Yourself MySQL in 10 Minutes的示例:
mysql> SELECT c.name, o.order_date
-> FROM customers c
-> LEFT OUTER JOIN orders o
-> ON o.customer_code = c.customer_code
-> AND o.order_date BETWEEN '2006-02-01' AND '2006-02-28';
+-------------------------+------------+
| name | order_date |
+-------------------------+------------+
| Presidents Incorporated | NULL |
| Science Corporation | 2006-02-02 |
| Science Corporation | 2006-02-05 |
| Musicians of America | 2006-02-01 |
| Musicians of America | 2006-02-02 |
+-------------------------+------------+
5 rows in set (0.00 sec)
此外,我还会使用AS
关键字在查询中直接命名我想要的列,而不必使用get_friend_user_details_result
来完成您想要的内容。
要在单个查询中获得您想要的内容,可以提高速度,并且在很多情况下还可以清理您的代码。