Jump to content

Accessing a POSTED variable in a for loop?


JimRowan

Recommended Posts

Well, I've spent the last 3 hours trying to figure this one out on my own, but my hairs are noticably turning grayer, so I would be forever thankful if I could get any advice on this.

 

I designed a flash game in AS3 that uses a high score list of an unknown length.  my AS3 code will POST to php a variable(counter) that stores the amount of high scores in the list, and also a variable for each name and score entry(nameSent1, nameSent2, etc...).

 

If I try to explicitly access these variables in my php file as such:

$name = $_POST['nameSent3'];

I have no problems - $name extracts the right information, so I know my AS3 is correctly posting the information.  Now, when I try to access all that information in a for loop, I have no idea how to properly address my POSTED variable name.  Here's what I have:

<?php

$score = array();
$name = array();

$count = $_POST['counter'];
for($i=1; $i<=$count; $i++){
$score[$i] = $_POST['scoreSent'].=$i;
$name[$i] = $_POST['nameSent'.=$i];
}


$myScores = $name[1];


$myFile = "highscores2.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $myScores);
fclose($fh);

?>

That way isn't flying with the PHP gods.  I hope you can see what I'm trying to do: I know that each of my variables being sent to PHP are named "nameSent"+integer.

 

If there's anyone out there that knows how to do what I'm trying to do, I would greatly appreciate the help.

What about accessing them differently, using foreach?

$myScores = '';
foreach($_POST as $val){
  $myScores .= $val."\r\n";
}

$myFile = "highscores2.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $myScores);
fclose($fh);

 

You can modify how your data is sent to make it easier.  Such as a concatenation: name|score

$count = $_POST['counter'];
for($i=1; $i<=$count; $i++){
   $score[$i] = $_POST['scoreSent' . $i];
   $name[$i] = $_POST['nameSent'. $i];
}

 

Try that.

 

Thanks, you definitely put me on the right track.  It worked with this:

for($i=1; $i<=10; $i++){
   $score[$i] = $_POST['scoreSent' . ($i)];
   $name[$i] = $_POST['nameSent' . ($i)];
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.