php – How to use the values ​​of a column as an index in an array?


Consider the following table configuraciones

id |  nombre  |  valor  |  categoria
1  |   color  |  azul   |  personal
2  |   día    |  martes |  personal
3  |   ciudad |  Limón  |  general

Suppose there are many more configurations classified by category. I have tried to run a query that allows me to get those settings:

$q = Doctrine_Query::create()
    ->from('Configuracion c')
    ->where('c.categoria = ?', $categoria);

Everything works great up to this point. But is there a way to create a query that will return a sorted structure in categories? For example:

$resultado = $q->execute(); 

//la idea acá es usar la columna "nombre" como índice:
$color = $resulSet['color']  

//imprimir el valor de color:
echo $color['valor'];  //debería imprimir "azul"


The trick is to use the INDEX BY argument.

Query class

The following example illustrates a statement using the Doctrine Query Language :

$consulta = $em->createQuery('
    SELECT c
    FROM modelos\Configuracion c 
    INDEX BY c.nombre
    WHERE c.category = :category');
$consulta->setParameter('category', 'personal');

We specify the type of result as an Array to be able to manipulate it by indexes:

$configuraciones = $consulta->getResult(Query::HYDRATE_ARRAY); 

We show the value:

echo $settings['color']['valor'];  // imprime "azul"


Example using theQueryBuilder object:

$consulta = $em->createQueryBuilder();
// el tercer argumento indica el índice del eventual resultado
$consulta->from('modelos\Configuracion', 'c', 'c.nombre');  
$configuraciones = $consulta->getQuery()->getResult();

Now the value is only accessed through the object's functions:

$color = $configuraciones['color'];
$valor = $color->getValor(); // devuelve "azul"
Scroll to Top