Pregunta

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

¿Fue útil?

Solución

$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.

Otros consejos

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.

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

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

echo $deuser['username'];`
Licenciado bajo: CC-BY-SA con atribución
scroll top