2012-07-04 62 views
-1

我想从数据库查询创建一个数组。我想通过他们的ID选择10个随机问题,并把它们放入一个数组中,只是这个ID,我不希望它像[0]=>array('1'),[1]=>array('2'),我想简单地说,array('1','2','3')等。从数据库结果创建一个数组

他们之后在阵列中,我希望能够检查ID是否在阵列中

+2

'阵列的枚举阵列([0] => '1',[1] => '2',[2] => '3')'与'array('1','2','3')'相同。你可以用'print_r(array('1','2','3'))'来检查。至于检查数组中有什么,看看[in_array函数](http://php.net/manual/en/function.in-array.php) –

+1

如果你创建数组('1','2' ,'3')你会得到[0] =>'1',[1] =>'2',[3] =>'3'。 ['id'=> 1],['id'=> 3],['id'=> 4],['id'=> 5],我推荐获取更多关于PHP –

+0

的信息。 ] NOT [0 => 1,1 => 3,...] –

回答

0
try { 
    $pdo = new PDO([dsn], [username], [password]); 
    $sql = " 
     SELECT ID 
     FROM [tablename] 
     ORDER BY RAND() 
     LIMIT 10 
    "; 
    $statement = $pdo->prepare($sql); 
    if (!$statement) { 
     //error handling here 
    } 
    $result = $statement->execute(); 
    if (!$result) { 
     //error handling here 
    $array = array(); 
    while (list($id) = $statement->fetch(PDO::FETCH_NUM)) { 
     $array[] = $id; 
    } 
    $statement = NULL; 
} catch (PDOException $e) { 
    //error handling here 
} 

这应该离开ID的

相关问题