1

I'm creating a game where when a timer ends the user can enter their name. I pass the name and score to a PHP file with AJAX. That PHP file adds it to an XML file. I loop through it to create a table holding the scores and it's then returned to AJAX and I then output it on the screen with jQuery. I have all of this working fine right now.

What I want to accomplish is this: 1. After the score is added to the XML file I want to order the nodes according to score, in descending order 2. I then want to populate the table with the values in order. I'd also like to limit it to only the top 10 scores.

Basically where I'm running into problems coming up with a solution is the ordering. Once the XML is ordered populating the table and limiting it to 10 should be pretty straight forward. Any suggestions on how I should do this?

XML : http://people.rit.edu/lxl1500/Prog4/Project%202/scoreboard.xml

jQuery Ajax call:

function addScore(score,name){
    var url = 'scoreboard.php';
    $.post(url,{Score:score, Name:name},function(data){
    $('#score').html(data).show();
   });
}

scoreboard.php:

<?php
$score = $_POST['Score'];
$name = $_POST['Name'];

if($name == ''){
    $name = 'Player'.rand(0,5000);
}

$scoreboard = new domDocument;
$scoreboard->load('scoreboard.xml');

$root=$scoreboard->documentElement;

$entry = $scoreboard->createElement('entry');

$userScore = $scoreboard->createElement('score',$score);

$userName = $scoreboard->createElement('name',$name);

$entry->appendChild($userName);
$entry->appendChild($userScore);

$root->appendChild($entry);

$scoreboard->save('scoreboard.xml');

$scores = $scoreboard->getElementsByTagName('entry');

$string = '<table id="score-table" cellspacing="10"><tbody><tr><th align="left">User</th><th align="left">Score</th></tr>';


foreach($scores as $score){
    $getScore = $score->getElementsByTagName('score')->item(0)->nodeValue;
    $getPlayer = $score->getElementsByTagName('name')->item(0)->nodeValue;
    $string.="<tr><td>$getPlayer</td><td>$getScore</td></tr>";
}

$string.='</tbody></table>';

echo $string;

?>

Any help would be greatly appreciated! Thanks.

4

1 に答える 1

0

並べ替えられた XML ファイルを作成できます。つまり、次のような並べ替えられた順序でノードを xml ファイルに追加します。

$entries = $root->getElementsByTagName('entry');

$added = false;
foreach ($entries as $item) {
    if ($score <= $item->getElementsByTagName('score')->item(0)->nodeValue) continue;
    $root->insertBefore($entry, $item);
    $added = true;
    break;
}

// if not yet added, add it
if (!$added) {
    $root->appendChild($entry);
}

これが機能するには、ファイルをソートする (または空にする) 必要があります。

于 2013-02-14T22:31:59.737 に答える