-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 回答