Pdo::fetch_group

I have this bit of php

$sql = 'SELECT type, asset_id FROM assets';

echo $sql;
$result = $pdo->query($sql);

$assetArray = $result->fetchAll(PDO::FETCH_GROUP);

echo '<pre>';print_r($assetArray);echo '</pre>';

the result,
Array
(
)
but since im grouping by type, shouldnt the result be more like
Array
( [type1] = Array ()
[type2] = Array()
)
so if I

count($pduArray[type1];

I get 0

For a fetchAll() statement to return an empty array, it means that the query didn’t return any data. Does that table, in the selected database have any data in it? What does that same code produce without the PDO::FETCH_GROUP parameter?

1 Like

ok, I added an asset, and now the result
Array
(
[rack] => Array
(
[0] => Array
(
[asset_id] => 1
[0] => 1
)

    )

)
Which seems to index by type.
But I have like 12 types and I want to be able to show that if the type is missing, it has 0 results…

I tried

<?php if(array_key_exists('ats',$assetArray)) { echo "0"; } else { echo count($assetArray['ats']); } ?>

But I get an error

I thought testing for the index would work.
oh, duh! My logic was backwards, forgot the !

1 Like

I hope you are doing that dynamically, using a data-driven design, by having a data structure (array or database table) that you loop over to produce the result using one instance of the logic, rather than writing out code for every possible value?

Programming is a tedious activity. You should be getting the computer to do repetitive work for you, rather than spending your time pressing keys for 12 sets of code, that you than have to find and edit if a new value (type) gets added.