Hello i have one quick question.
I'm using Doctrine 2 and i need to get pairs from specific table as array. For example, i have table "Category" with columns ('id', 'name', 'description' , ...) and i want to get all rows in array format (category.id=>category.name) as follow:
array(
7 => 'News',
8 => 'Sport',
11 => 'Work'
)
(I have only 3 categories with ids 7,8,11 in this example).
Is there some simple and quick way how to do it?
Try this
$result = $query->getResult(Query::HYDRATE_ARRAY);
OR
$result = $query->getArrayResult();
For more Info. See link
To convert categoryId
to array key and categoryName
to value
$newArr=[];
foreach($result as $cat){
$newArr[] = [$cat['id'] => $cat['name']];
}
Get results as array
$result = $query->getResult(Query::HYDRATE_ARRAY);
You can then use a for each to modify your results as follows:
$modifiedResults = array();
foreach ($results as $row)
{
array_push($modifiedResults, array($row['id'] => $row['names']));
}
I think, in that case you should write your own custom hydrator Custom Hydration Modes
It's much simpeler than previous answers. You can do this by using a PDO constant and Doctrine's Database Access layer (DBAL).
From a controller :
$dbal = $this->getDoctrine()->getConnection();
$idsAndNames = $dbal->executeQuery('SELECT id, name FROM Categories')->fetchAll(\PDO::FETCH_KEY_PAIR);
This will result in the array from your question.