Create PHP array from MySQL column

前端 未结 11 946
花落未央
花落未央 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:02

    Loop through the result:

    $result = mysql_query(...);
    $data = array();
    while ($row = mysql_fetch_array($result)) {
        array_push($data, $row["columnyouwant"]);
    }
    
    0 讨论(0)
  • 2020-12-03 08:04
    // I'm using this for years and it works very good !! it's easy and logic
    $translate = array();
    
    while ($row = mysql_fetch_assoc($result))
      {
          $cullomnkey = $row['translshort']; // is what you want the key to be 
          $translate[$cullomnkey] = $row[$language]; // this is the key and the value in the array 
      }
    
    0 讨论(0)
  • 2020-12-03 08:13

    you could loop through the array, and create a new one, like so:

    $column = array();
    
    while($row = mysql_fetch_array($info)){
        $column[] = $row[$key];
    //Edited - added semicolon at the End of line.1st and 4th(prev) line
    
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 08:16

    If none of the above work, try:

    while( $row = mysqli_fetch_assoc( $result)){
         $array[] = $row['id'];
    }
    
    mysql_fetch_assoc is deprecated.
    
    0 讨论(0)
  • 2020-12-03 08:17

    There is no function to do this using the mysql extension, you can do this:

    $result = array();
    while ($row = mysql_fetch_array($r, MYSQL_NUM)) {
        $result[] = $row[0];
    }
    

    It is apparently marginally faster to fetch the columns in a numerically indexed array, and there is no real benefit here to having the associative array format.

    0 讨论(0)
提交回复
热议问题