2017-10-11 17 views
0
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"]; 
     } 
} 

我想獲得前5名高值從所有的JSON文件中的「玩家」文件夾中,我只知道如何從所有文件值,但不要不知道如何選擇5更高。有人可以幫忙嗎?如何獲得文件夾內的JSON文件前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

顯示'$ json'數組的示例。 – AbraCadaver

+0

好吧,我編輯後,你可以在這裏看到它 – GuyWhoDoThings

+0

你放棄了? – AbraCadaver

回答

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

0

您需要$levels[]打造level秒的數組要覆蓋每一次$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,這樣你可以傳入它?

相關問題