admin管理员组

文章数量:1334694

Please i need assistance in converting objects that is returned from $wpdb->get_results into arrays so that i can call them values like $query['username'] instead of using $Query->username

because my method of doing it is not flexible enough and it makes me write many codes by manually creating those column as array just like this code below
$data = array('username = $query->username, email = $query->email');
but i believe there is a simple way to do this automatically without having to retype all column names one by one

Please i need assistance in converting objects that is returned from $wpdb->get_results into arrays so that i can call them values like $query['username'] instead of using $Query->username

because my method of doing it is not flexible enough and it makes me write many codes by manually creating those column as array just like this code below
$data = array('username = $query->username, email = $query->email');
but i believe there is a simple way to do this automatically without having to retype all column names one by one

Share Improve this question asked Jun 3, 2020 at 8:48 pandglobalpandglobal 431 silver badge9 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 1

$wpdb->get_results has a second parameter that lets you specify what kind of return value you want:

For example:

$data = $wpdb->get_results( $query, ARRAY_A );

Here you get an associative array back.

global $wpdb;
$data =  $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}users", ARRAY_A );

foreach($data as $user){ 
$deuser = $user;
}

echo $deuser['username'];`

Hey you can try this to use the Object in array format:

global $wpdb;
$data =  $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}users", OBJECT );
$data = json_decode( json_encode($data), true );
echo $data[0]['user_email'];

Also, you can use the unset() method to remove unwanted columns from the array. By using this way you can achieve.

本文标签: phpHow to convert objects into arrays