我可以在循环中使用php变量创建数组吗?

时间:2013-12-04 04:26:25

标签: php arrays

我可以在循环中使用php变量创建一个数组吗?

<?php
for($i=5;$i<=100;$i++)
{
    $sql = "SELECT * FROM users WHERE id = '$i' order by id asc";
    $result = mysql_query($sql);
    $datas=mysql_fetch_array($result);{
    $username = stripslashes(str_replace('\r\n', '<br>',($datas['username'])));
    }
    ${'name' . $i} = $username;
}
?>

好的,现在我有php变量$ name1- $ name100

然后我想用php变量$ name1- $ name100

创建数组
$my_array = array(php variable $name1-$name100);

我该怎么办?

1 个答案:

答案 0 :(得分:0)

只需修改存储用户名的方式:

$my_array = array();
for ( $i = 5; $i <= 100; $i++ ) {
    $sql = "SELECT * FROM users WHERE id = '$i' order by id asc";
    $result = mysql_query($sql);
    $datas = mysql_fetch_array($result);
    $username = stripslashes(str_replace('\r\n', '<br>',($datas['username'])));
    $my_array[] = $username; // push usernames into array
}

此外,您不应该运行这么多查询,所以我建议这样的事情:

$usernames = array();
$query = "SELECT * FROM users WHERE id >= 5 AND id <= 100 ORDER BY id ASC";
$result = mysql_query( $query );

if ( mysql_num_rows( $result ) > 0 ) {
    while ( $data = mysql_fetch_assoc( $result ) )
        $usernames[] = stripslashes( str_replace( '\r\n', '<br>', $data['username'] ) );
}