Create PHP array from MySQL column

前端 未结 11 1015
花落未央
花落未央 2020-12-03 07:54

mysql_fetch_array will give me an array of a fetched row. What\'s the best way generate an array from the values of all rows in one column?

11条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 08:13

    If you use PDO instead of php-mysql the return value of PDO::query() implements the Traversable interface, meaning you can use it e.g. with foreach() (unlike the mysql result resource you get from mysql_query).

    foreach( $pdo->query('SELECT x,y,z FROM foo') as $row ) {
    

    And in case this does not suffice and you really, really need an array (i.e. get_class($x)==='Array'), there's the fetchAll() method.

提交回复
热议问题