I have an table like this:
id //not index | origin |
---|---|
1 | germany |
1 | usa |
2 | usa |
2 |
I want to get every Entity witch has an origin (!= '') but in a multidimensional Array, sorted by the id, looking like this:
[
[
{
'id': '1',
'origin': 'germany'
},
{
'id': '1',
'origin': 'usa'
},
],
[
{
'id': '2',
'origin': 'usa'
}
]
]
is this even possible with a query or do I have to do this in PHP?
CodePudding user response:
You can remove the empty fields like this for e.x.
<pre><?php
// Source before
$before = array();
$before[] = array("1" => "germany");
$before[] = array("1" => "usa");
$before[] = array("2" => "usa");
$before[] = array("2" => "");
print_r($before);
// Source after
$after = array();
foreach ($before as $key => $value) {
// Only add value, if aviable
foreach ($value as $key2 => $value2) {
if (!empty($value2)) {
$after[] = array($key2,$value2);
}
}
}
print_r($after);
Result:
Array
(
[0] => Array
(
[1] => germany
)
[1] => Array
(
[1] => usa
)
[2] => Array
(
[2] => usa
)
[3] => Array
(
[2] =>
)
)
Array
(
[0] => Array
(
[0] => 1
[1] => germany
)
[1] => Array
(
[0] => 1
[1] => usa
)
[2] => Array
(
[0] => 2
[1] => usa
)
)
CodePudding user response:
You can use QueryBuilder in your repository to do that.
$qb = $this->createQueryBuilder('your_alias')
->select('your_alias.id, your_alias.origin');
$qb
->where('your_alias.origin IS NOT NULL')
->orderBy('your_alias.id');
return $qb->getQuery()->getResult();
Regards,