Monday, 2 February 2015

PDO to Array

PDO to Array

PDO result sets return an array of arrays. This is great for most applications except if you need a single dimension array result set from a query that selects only two fields. I was recently populating some dropdown menu's with results from a database, so the query looked like this
SELECT category_id, category_name from phpro_categories
I again needed to populate other drop a products dropdown and several others and found myself writing out code over and over to do the same task, make the array of arrays from PDO into a single dimensional array using the id as key and the name of the second field as the value. So when I fetched my I used this.
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
This snippet below will take the result set from PDO and create an array like this
Array
(
    [1] => romance
    [2] => Thriller
    [3] => Adventure
    [4] => Sport
    [5] => autobiography
    [6] => non fiction
)

<?php
/**
 *
 * @convert pdo multi-d array to single d
 *
 * @param array $result
 *
 * @return $array
 *
 */
 
function pdo2array($result){
 
$new=array();
 foreach ( 
$result as $val )
 {
    
$keys array_keys($val);
    
$new[$val[$keys[0]]] = $val[$keys[1]];
 }
 return 
$new;
 }
?>

0 comments:

Post a Comment