Zagloo
Zagloo

Reputation: 1387

Symfony2 - get array from SQL

Before to use Symfony I wrote my code in PHP. This was my code :

$query_nb_cat = "SELECT titre_categorie_nv1, COUNT(*) 
    FROM Tutoriels 
    INNER JOIN Groupe_de_categories 
    ON Tutoriels.id_groupe_categorie = Groupe_de_categories.id_groupe_categorie 
    WHERE tutoriel_controle='non' 
    GROUP BY titre_categorie_nv1";

$nb_cat = mysqli_query($BDD_connect, $query_nb_cat)or die(log_mysql($query_nb_cat));
    $row_nb_cat = mysqli_fetch_assoc($nb_cat);
do {
    $tableau_nb_cat[]=array(
        'titre_cat_nv1'=>$row_nb_cat['titre_categorie_nv1'],
        'compte_cat_nv1'=>$row_nb_cat['COUNT(*)'],
    );
} while ($row_nb_cat = mysqli_fetch_assoc($nb_cat));

$val_cat=array(
    'valeur_retour'=>$tableau_nb_cat
);

The response was like that (in an array) :

'Arts & Loisirs'  => '18' 
'Cuisine' =>  '55' 
'Informatique'=> '9' 

Now with Symfony2 my query is like that:

$result = $em->createQuery("SELECT b.titreCategorieNv1, COUNT(b.titreCategorieNv1) 
                FROM Video2LearnBddBundle:Tutoriels p
                INNER JOIN p.idGroupeCategorie a
                INNER JOIN a.titreCategorieNv1 b
                WHERE p.tutorielControle='non'
                GROUP BY b.titreCategorieNv1")
                ->getResult();

The Dump result is like that :

array (size=3)
  0 => 
    array (size=2)
      'titreCategorieNv1' => string 'Arts & Loisirs' (length=14)
      1 => string '18' (length=1)
  1 => 
    array (size=2)
      'titreCategorieNv1' => string 'Cuisine' (length=7)
      1 => string '55' (length=1)
  2 => 
    array (size=2)
      'titreCategorieNv1' => string 'Informatique' (length=12)
      1 => string '9' (length=1)

How can I have in return a response like that (the same like in my PHP code) ??:

  'Arts & Loisirs'  => '18' 
  'Cuisine' =>  '55' 
  'Informatique'=> '9' 

Thank you

Upvotes: 0

Views: 132

Answers (1)

ghostika
ghostika

Reputation: 1503

Just change the last function:

$em->createQuery('YOUR SQL QUERY')->getArrayResult()

EDIT:

Sorry, checked again your code, but I don't see, how could your old code produce that output, cause in the do while, you are creating a new array with array element and 2 separate keys. There is no direct hydrate mode for that, you have to run a foreach for example.

Upvotes: 2

Related Questions