dongsuoxi1790 2015-06-16 06:45
浏览 21
已采纳

PHP - 如何将更改的变量设置为新数组

I'm trying to get the output array to be set as a new array with the updated (sorted) output. The purpose of this is to get the new variable to be ordered: [0,1,2,3,4] as now it is being sorted by the key and therefore the order of the actual array has shifted, so its more like: [3,1,4,2]. The code is listed below:

//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 
 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);

The score.txt contains the following:

35|Nathan 50|Matt 45|Sam 20|Jono 40|Bob 30|Roman 25|Zac 15|Larry 10|Thomas 5|Josh

The output is currently the following (including the added $name and $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"]}

As you can see, it orders it by their score: 55,50,45 and the array is just reordered: 10,1,2.

How can I have the same output, but now the output would be:

{"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"]}

The output is now: 0,1,2,3.. which is ordered from highest high score: 55,50,45...

Thanks in advance.

  • 写回答

2条回答 默认 最新

  • duanfei1987 2015-06-16 07:09
    关注

    arsort() would reverse order AND maintain index key association, I think what you're looking for is rsort() it will reverse sort the array and reset the index key association

    Change the following bit in your code to use rsort()

    //Sort it from high to low
    rsort($lines);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本