Create PHP array from MySQL column

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

    If you don't need other information in that table, you can query for only the column you need and it makes it all more easy:

    $query = mysql_query("SELECT * FROM table WHERE id='$int' LIMIT 1");
    $column = array();
    $column  = mysql_fetch_array($query);
    
    0 讨论(0)
  • 2020-12-03 08:20
    $result = mysql_query("SELECT columnname FROM table WHERE x=y");
    
    $columnValues = Array();
    
    while ( $row = mysql_fetch_assoc($result) ) {
    
      $columnValues[] = $row['columnname'];
    
    }
    
    0 讨论(0)
  • 2020-12-03 08:20

    you can do this :

            $columns = array();
            $i=1;
            while( $row = mysql_fetch_array($sql) )
               {
                  $columns [$i]=$row['value'];
                  $i++;
               }
    
    0 讨论(0)
  • 2020-12-03 08:25

    Use a while loop to get the records and store them in an array:

    $array = array();
    while ($row = mysql_fetch_array()) {
        $array[] = $row['column-x'];
    }
    
    0 讨论(0)
  • 2020-12-03 08:28
    $query = mysql_query('SELECT * from yourTable');
    function mysql_field_array( $query ) {
        $field = mysql_num_fields( $query );
        for ( $i = 0; $i < $field; $i++ ) {
            $names[] = mysql_field_name( $query, $i );
        }
        return $names;
    }
    
    $fields = mysql_field_array( $query );
    $output = implode( ',', $fields );   //outputs the columns names
    //echo count( $fields );  //this use if you want count of columns.
    $columns = '{\"fields\":\".json_encode($output).\"}';
    echo $columns; //for JSON output
    
    0 讨论(0)
提交回复
热议问题