Pierre-max Halldegare
Pierre-max Halldegare

Reputation: 63

Get array with key and value as my select attributes in DQL

I'm doing a query using DQL

$query = $this->createQueryBuilder('i')
      ->select('(i.sortiesNoSortie)','COUNT(i.participantsNoParticipant)')
      ->groupBy('i.sortiesNoSortie');


$result = $query->getQuery()->getArrayResult();

but i'm getting this

array:3 [
  0 => array:2 [
    1 => "76"
    2 => "1"
  ]
  1 => array:2 [
    1 => "82"
    2 => "1"
  ]
  2 => array:2 [
    1 => "83"
    2 => "1"
  ]
]

And I want to get that in a simple array with key and value from my select

76 => 1
82 => 1
83 => 1 

Is that possible ?

Upvotes: 1

Views: 1342

Answers (1)

SteppingHat
SteppingHat

Reputation: 1362

For obvious reasons, the result is a 2D array as it is representing the rows and columns that you would receive when executing the query. From the top of my head, there isn't a doctrine provided function to transform it into your desired format.

You can however use PHP to reformat the array for you.

$result = $this->createQueryBuilder('i')
  ->select('(i.sortiesNoSortie)','COUNT(i.participantsNoParticipant)')
  ->groupBy('i.sortiesNoSortie')
  ->getQuery()
  ->getArrayResult();

$output = array();
foreach($result as $row) {
    $output[$row[0]] = $row[1];
}

While it seems at first that this is not ideal, realistically if doctrine were to implement something to format it the way you want it, it would most likely do something similar and just wrap it in a nice function for you.

Having said that, there may be a nicer way to process the data using PHP other than a foreach loop. Either way, don't shy away completely from reformatting your data in PHP after getting it from doctrine. Obviously this would be a case by case thing but it seems that you are processing small amounts of data, so the extra processing won't be an issue.


Edit

Thanks @Matteo for reminding me. array_column is the function that you can use to replace the foreach loop.

$output = array_column($result, 1, 0);

Upvotes: 3

Related Questions