将自定义表转换为数组

时间:2013-03-09 作者:LukasFT

如何获取我这样创建的表:

global $wpdb; //Get all the wordpress database stuff
$table_prefix = $wpdb->base_prefix; //Get the global prefix for all sites (on a multisite installation)
$table_name = $table_prefix.\'wpaa\';//Add   wpaa   behind the prefix 

$sql = "CREATE TABLE IF NOT EXISTS `".$table_name."` (....) "; //Create table and its rows. (Rows are ...\'d out)

require_once( ABSPATH . \'wp-admin/includes/upgrade.php\' ); //Require something you have to include
dbDelta( $sql ); //Make the actual query
并以数组的形式从中获取所有数据。

我知道在普通PHP中该怎么做(没有wordpress):

$sql = \'SELECT id,foo,bar FROM wp_wpaa\';
$result = mysql_query($sql) or die(\'Error at looking up in database\');
$array = mysql_fetch_array($result);

1 个回复
最合适的回答,由SO网友:fuxia 整理而成

$wpdb->get_results(); 返回格式有第二个参数:

/**
 * Retrieve an entire SQL result set from the database (i.e., many rows)
 *
 * Executes a SQL query and returns the entire SQL result.
 *
 * @since 0.71
 *
 * @param string $query SQL query.
 * @param string $output Optional. 
 * Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants. 
 * With one of the first three, return an array of rows indexed from 0 by SQL 
 * result row number.
 *  Each row is an associative array (column => value, ...), a numerically 
 *      indexed array (0 => value, ...), or an object. ( ->column = value ), 
 *      respectively.
 *  With OBJECT_K, return an associative array of row objects keyed by the 
 *      value of each row\'s first column\'s value. Duplicate keys are discarded.
 * @return mixed Database query results
 */
function get_results( $query = null, $output = OBJECT ) {
这将返回一个数组:

$result = $wpdb->get_results( $sql, ARRAY_A );

结束