public function onRun(int $currentTick){
foreach (glob($this->plugin->getDataFolder()."/players/*.json") as $plData) {
$str = file_get_contents($plData);
$json = json_decode($str, true);
$levels = $json["level"];
}
}
我想从"播放器"中的所有json文件中获得前5个更高的值文件夹,我只知道如何从所有文件中获取该值,但不知道如何选择5更高。有人可以帮忙吗?
编辑:Json文件如下所示:
{
"coins": 0,
"rank": "Guest",
"accept_friends": true,
"reward_time": 1440,
"level": "29",
"bio": "Today is very cool!c",
"progress": 24.939999999999998,
"local_ip": "10.0.0.1",
"registred": true,
"logged": true
}
答案 0 :(得分:0)
使用usort
!
创建一个能够处理排序的函数:
function levelSort($a, $b)
{
return $a['level']>$b['level'];
}
接下来将您的玩家存储到阵列中,对其进行排序并返回前五个元素:
public function onRun(int $currentTick){
$players = []; // declare aray with proper scope
foreach (glob($this->plugin->getDataFolder()."/players/*.json") as $plData) {
$str = file_get_contents($plData);
$json = json_decode($str, true);
$players[] = $json; // save to array
}
usort($players, 'levelSort'); // sort using custom function
return array_slice($players, 0, 5); // return 5 elements
}
应该有效。没有测试过:D
当然这个例子假设每个$json
都是一个数组并且$json['level']
存在且是int
答案 1 :(得分:0)
您需要使用level
构建$levels[]
数组,因为每次都会覆盖$levels
。然后反向排序并切片前5:
public function onRun(int $currentTick){
foreach (glob($this->plugin->getDataFolder()."/players/*.json") as $plData) {
$str = file_get_contents($plData);
$json = json_decode($str, true);
$levels[] = $json["level"];
}
rsort($levels);
return array_slice($levels, 0, 5);
}
如果要返回整个前5个数组:
public function onRun(int $currentTick){
foreach (glob($this->plugin->getDataFolder()."/players/*.json") as $plData) {
$str = file_get_contents($plData);
$results[] = json_decode($str, true);
}
array_multisort(array_column($results, 'level'), SORT_DESC, $results);
return array_slice($results, 0, 5);
}
为什么要传递参数$currentTick
而不使用它?也许用$currentTick
代替5,这样你就可以传入它了吗?