有可能做这样的事情吗?我是新手所以不知道!
//row 1 in mysql array
$var = "hello";
$id = 1;
//row 2 in mysql array
$var = "bye";
$id = 2;
//Closing while loop
//Is the following possible?
echo $var1; //outputs "hello"
echo $var2; //outputs "bye"
不像您想要的那样,您可以使用数组:
$var[1] = "hello";
$var[2] = "bye";
echo $var[1];
echo $var[2];
我会这样做
$id = 1;
$var[$id] = "hello";
$id = 2;
$var[$id] = "bye";
echo $var['1'];
echo $var['2'];
// or
echo $var[$id];
// Define them both as arrays
$var = array();
$id = array();
// In your loop
$var[] = "hello";
$id[] = 1;
// Next iteration
$var[] = "bye";
$id[] = 2;
// Printing them out
echo $var[0]; // prints out "hello"
echo $var[1]; // prints out "bye"
使用数组^^
或者:
$rows = array();
// In your loop
$rows[] = array("id" => 1, "var" => "hello");
// Next iteration
$rows[] = array("id" => 2, "var" => "bye");
// Print them out
echo $rows[0]["var"]; // Prints hello
echo $rows[1]["var"]; // Prints bye
你提到了 MySQL。因此,您想要实现的更完整示例是:
$var = array();
$id = array();
while ($row = mysql_fetch_assoc($result)) {
$var[] = $row['text']; // don't know how the column is named
$id[] = $row['id'];
}
echo $row[0]; // hello
echo $row[1]; // bye
使用循环变量i
:
$var = array();
$i = 1;
while ($row = mysql_fetch_assoc($result)) {
$var[$i] = $row['text']; // don't know how the column is named
$i++;
}
echo $row[1]; // hello
echo $row[2]; // bye