John Davidson

php - Symfony query builder get value without keys


I have a problem getting the result I want.
I always get the key together with the value but I just want to get the value.

I have some code like this:

->from(Article::class, 'a')

and my result is:

Array ( [0] => Array ( [id] => 111 ) 
[1] => Array ( [id] => 222 )

but I want it to be like:

Array ( [0] => 111 [1] => 222 )

I have tried to user ->getResult(), ->getArrayResult() and stuff like that but I never came to the right solution.

Thank you very much!

My Answer:
> $qb = $this->createQueryBuilder('u')
> ->select('')
> ->getQuery()
> ->getResult();
> foreach ($qb as $result) {
> $name = $result['name'];
> // do something with $name
> }

In this code, `$qb` is an array of results where each result is an associative array with keys and values. To get just the value without the key, you can access the value directly without specifying the key. In this case, you can access the value of the `name` field directly like `$result['name']`.

If you want to get the values without keys in a more structured way, you can use the `getScalarResult()` method instead of `getResult()`. This will return an array of scalar values without keys.

Here's an example:

$qb = $this->createQueryBuilder('u')

foreach ($qb as $result) {
$name = $result[0];
// do something with $name

In this code, `$qb` will be an array of arrays where each inner array contains a single scalar value without a key. You can access the value directly using the index `0`.

Rate this post

3 of 5 based on 1654 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us