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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Yes, 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
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0