My query is:
$var = $wpdb->get_results("SELECT field FROM {$wpdb->prefix}table", ARRAY_A);
var_dump($var);
it returns someting like array(2) { [0]=> array(1) { ["field"]=> string(5) "test1" } [1]=> array(1) { ["field"]=> string(t) "test2" }. I.e. each item is a row with a single name-value pair.
What I want is array(2) { [0]=> string(5) "test1" [1]=> string(5) "test2" }
Currently I achieve it like this:
$var = $wpdb->get_results("SELECT field FROM {$wpdb->prefix}table");
foreach($var as $v_key => $v_val) $var[$v_key] = $v_val['field'];
var_dump($var);
Is there a shorter way to do this?
My query is:
$var = $wpdb->get_results("SELECT field FROM {$wpdb->prefix}table", ARRAY_A);
var_dump($var);
it returns someting like array(2) { [0]=> array(1) { ["field"]=> string(5) "test1" } [1]=> array(1) { ["field"]=> string(t) "test2" }. I.e. each item is a row with a single name-value pair.
What I want is array(2) { [0]=> string(5) "test1" [1]=> string(5) "test2" }
Currently I achieve it like this:
$var = $wpdb->get_results("SELECT field FROM {$wpdb->prefix}table");
foreach($var as $v_key => $v_val) $var[$v_key] = $v_val['field'];
var_dump($var);
Is there a shorter way to do this?
Share Improve this question asked Nov 7, 2020 at 7:30 ArtemArtem 3152 silver badges13 bronze badges1 Answer
Reset to default 5Yes, there is.
If you want to retrieve just one column from the database table, i.e. all row values for that column, you can use wpdb::get_col()
.
$values = $wpdb->get_col( "SELECT field FROM {$wpdb->prefix}table" );
foreach ( $values as $value ) {
// your code
}