我目前有一个带有用户条目TABLE的数据库 - 我在其中查询类似的内容:
user_id: 1
user_point: 20
user_id: 1
user_point: 50
user_id: 2
user_point: 10
此数据保存在一个数组中,如下所示:
$highscoreData = array();
while ($row = mysql_fetch_assoc($res))
{
$highscoreData []= (object) array(
"user_id" => $row['user_id'],
"username" => $row['username'],
"user_firstname" => $row['user_firstname'],
"user_lastname" => $row['user_lastname'],
"user_point" => $row['user_point']
);
}
$feedback = $highscoreData;
如何将我的数组保存到基于user_id
的GROUP条目的位置,以便user_id = 1
只会在数组中出现一次,并且相关的已添加user_point
- 在这种情况下,它将等于“70分”?
我如何对数组进行排序,以便user_id
中user_point
数最多的for( var i = 0; i < highscoreData.length; i++ ){
//check if user_id = user_id - then perhaps save into a new array?
}
在数组中排在第一位?
对于问题1 - 我想做类似for循环的事情:
{{1}}
对于问题2 - 查看usort() - 但不完全确定如何在此上下文中使用
任何帮助,例子都会非常感激!
答案 0 :(得分:1)
使用它:我无法详细描述时间限制
<?php
$highscoreData []= (object) array(
"user_id" => 1,
"username" => 'name1',
"user_firstname" => "First Name 1",
"user_lastname" => "Last Name 1",
"user_point" => 20
);
$highscoreData []= (object) array(
"user_id" => 1,
"username" => 'name1',
"user_firstname" => "First Name 1",
"user_lastname" => "Last Name 1",
"user_point" => 50
);
$highscoreData []= (object) array(
"user_id" => 2,
"username" => 'name2',
"user_firstname" => "First Name 2",
"user_lastname" => "Last Name 2",
"user_point" => 80
);
$user_point_sum = array();
$users = array();
foreach($highscoreData as $array) {
//check if user_id = user_id - then perhaps save into a new array?
$user_id = $array->user_id;
$username = $array->username;
$user_firstname = $array->user_firstname;
$user_lastname = $array->user_lastname;
$user_point = $array->user_point;
if(!isset($user_point_sum[$user_id])) {
$user_point_sum[$user_id] = 0;
$user_info = new stdClass();
$user_info->user_id = $user_id;
$user_info->username = $username;
$user_info->user_firstname = $user_firstname;
$user_info->user_lastname = $user_lastname;
$users[$user_id] = $user_info;
}
$user_point_sum[$user_id] += $user_point;
}
arsort($user_point_sum);
$array_object = array();
foreach($user_point_sum as $user_id=>$user_point) {
$object = new stdClass();
$object->user_id = $user_id;
$object->username = $users[$user_id]->username;
$object->user_firstname = $users[$user_id]->user_firstname;
$object->user_lastname = $users[$user_id]->user_lastname;
$object->user_point = $user_point;
$array_object[] = $object;
}
var_dump($array_object);
?>
Output:
array
0 =>
object(stdClass)[6]
public 'user_id' => int 2
public 'username' => string 'name2' (length=5)
public 'user_firstname' => string 'First Name 2' (length=12)
public 'user_lastname' => string 'Last Name 2' (length=11)
public 'user_point' => int 80
1 =>
object(stdClass)[7]
public 'user_id' => int 1
public 'username' => string 'name1' (length=5)
public 'user_firstname' => string 'First Name 1' (length=12)
public 'user_lastname' => string 'Last Name 1' (length=11)
public 'user_point' => int 70