John Davidson

php - Symfony query builder get value without keys

0 comments
Message:


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:


$qb
->select('a.id')
->from(Article::class, 'a')
...
->getQuery()
->getArrayResult();

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('u.name')
> ->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:

php
$qb = $this->createQueryBuilder('u')
->select('u.name')
->getQuery()
->getScalarResult();

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

Comments




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