jonmrich
jonmrich

Reputation: 4323

PHP FetchAll to array

I'm trying to take a result from fetchAll and to take some of the data and put it into an array.

Relevant PHP:

  $catcodessql = "select distinct cat_code from mytable";
  $result2 = $dbh->query($catcodessql)->fetchAll(PDO::FETCH_ASSOC); 

This returns something like below:

array(4) {
 [0]=>
array(1) {
["cat_code"]=>
string(3) "edu"
 }
 [1]=>
 array(1) {
["cat_code"]=>
string(3) "inc"
}
[2]=>
array(1) {
["cat_code"]=>
string(3) "net"
 }
[3]=>
 array(1) {
["cat_code"]=>
string(3) "occ"
}

What I want is all those strings so I can dynamically put together this line later in my PHP:

$allcategories = array ('edu', 'inc', 'net', 'occ' );

So, I need to create a variable that will replace this part: 'edu', 'inc', 'net', 'occ'

I've tried a couple of while functions, but clearly they aren't right.

Upvotes: 1

Views: 288

Answers (2)

acontell
acontell

Reputation: 6932

If you only want to retrieve unique categories, You can do it directly with a query:

$stmt = $dbh->prepare("select GROUP_CONCAT( cat_code SEPARATOR ',') as cat_code from ( select distinct cat_code from mytable) as m"); 
$stmt->execute(); 
$row = $stmt->fetch();
$categories = explode(",",$row["cat_code"]);
var_dump($categories);

Upvotes: 1

AbraCadaver
AbraCadaver

Reputation: 78994

PHP >= 5.5.0 needed for array_column() or use the PHP Implementation of array_column()

$allcategories = array_column($result2, 'cat_code');

Or foreach over the query:

foreach($dbh->query($catcodessql) as $row) {
    $allcategories = $row['cat_code'];
}

Upvotes: 2

Related Questions