我试图将输出数组设置为具有更新(排序)输出的新数组。这样做的目的是获取要排序的新变量:[0,1,2,3,4]因为它现在按键排序,因此实际数组的顺序已经移位,所以它更像是: [3,1,4,2]。代码如下:
//Retrieve what is scored from the game
$name = $_GET["name"];
$score = $_GET["score"];
//Read a text file into an array, with each line in a new element
$filename = "score.txt";
$lines = array();
$file = fopen($filename, "r");
while(!feof($file)) {
//read file line by line into a new array element
$lines[] = explode("|",fgets($file));
}
fclose ($file);
//Append $name and $score into $lines
$lines[] = array($score,$name);
//Sort it from high to low
arsort($lines);
//Removes the 11th Highscore - As it is base 0, the 11th term is the 10th array
//unset($lines[10]);
//Remove the \n from the names - rtrim
for ($x = 0; $x <= 10; $x++) {
$lines[$x][1] = rtrim($lines[$x][1]);
$lines[$x][0] = intval($lines[$x][0]);
}
//print_r($lines);
echo json_encode($lines);
score.txt包含以下内容:
35|Nathan
50|Matt
45|Sam
20|Jono
40|Bob
30|Roman
25|Zac
15|Larry
10|Thomas
5|Josh
目前输出如下(包括添加的$ name和$ score):
{"10":[55,"Ball"],"1":[50,"Matt"],"2":[45,"Sam"],"4":[40,"Bob"],"0":[35,"Nathan"],"5":[30,"Roman"],"6":[25,"Zac"],"3":[20,"Jono"],"7":[15,"Larry"],"8":[10,"Thomas"],"9":[5,"Josh"]}
正如你所看到的,它按照得分排序:55,50,45,阵列只是重新排序:10,1,2。
如何获得相同的输出,但现在输出为:
{"0":[55,"Ball"],"1":[50,"Matt"],"2":[45,"Sam"],"3":[40,"Bob"],"4":[35,"Nathan"],"5":[30,"Roman"],"6":[25,"Zac"],"7":[20,"Jono"],"8":[15,"Larry"],"9":[10,"Thomas"],"10":[5,"Josh"]}
输出现在是:0,1,2,3 ..从最高分中排序:55,50,45 ...
提前致谢。
答案 0 :(得分:0)
arsort()会颠倒顺序并保持索引键关联,我认为你要找的是rsort()它将反向排序数组并重置索引键关联
更改代码中的以下位以使用rsort()
//Sort it from high to low
rsort($lines);
答案 1 :(得分:0)
Before 'json_encode($lines)' code, Put below code:-
$lines_temp = array();
foreach($lines as $k=>$v){
$lines_temp[] = $lines[$k];
}
$lines = $lines_temp;
echo json_encode($lines);