-5

while(row) ステートメントで新しい ID に値を代入してもうまくいきませんでした: これは簡単な例です。私のやりたいことを理解していただければ幸いです。ありがとう

<?php...

$id=0;
while(rows = mysql_fetch_data){
$id = $id + 1;

$teamname = rows['team'];
?>    

<script>
var team = '<?php echo $teamname; ?>';
var id = 'id_<?php echo $id; ?>';   

//Here I want to save the teamnames as javascript variable "id_1", "id_2" etc, which I can use outside the while statement. 

//For each row id = id_1, id_2, id_3, id_4.
//I want to make id_1 a variable which outputs teamname
//So that 
//var id_1 = team; //team 1
//var id_2 = team; //team 2


<?php    
}
?>

var id_1;
var id_2;
document.write("Teamname 1 = " + id_1 + "</br> Teamname 2 = " + id_2); //Here I want output of teamname 1 and 2.
</script>
4

2 に答える 2

2

チーム名のリストがあるため、個々の変数ではなく配列を使用することをお勧めします。

<?php

$teamnames = [];
while(rows = mysql_fetch_data){

  $teamnames[] = rows['team'];
}
?>    
<script>
var teamnames = <?php echo json_encode($teamnames); ?>;
</script>

次に、チーム名のクライアント側 JavaScript 配列になります。で出力できますがdocument.write、おそらくもっと良いオプションがあります。

ただしdocument.write、配列を使用するように更新したものは次のとおりです。

var n;
for (n = 0; n < teamnames.length; ++n)
{
  // Note: There's almost certainly a better choice than `document.write`
  document.write("Teamname " + (n + 1) + " = " + teamnames[n] + "</br>");
}
于 2013-10-03T08:33:30.967 に答える
0

コードを次のように置き換えると、目的の出力が得られるはずです...

<script>

<?php
//...

$id_counter = 1;   //Initialise counter
while($row = mysql_fetch_assoc()){
    echo 'var id_'.$id_counter.' = "'.$rows['team'].'";'; //Echo row in the format: var id_X = "team_name";
    $id_counter++; //Increment the counter
}

?>

document.write("Teamname 1 = " + id_1 + "</br> Teamname 2 = " + id_2); //Here I want output of teamname 1 and 2.
</script>
于 2013-10-03T08:37:35.283 に答える