我有一个这样的表:
id//not index | origin | 1 | 德国 | 1
---|---|
美国 | |
美国 | |
您可以像这样删除例如
的空字段。<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);
结果:
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
)
)
可以使用QueryBuilder
public function getAll() {
$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();
}
在你的控制器中:
$origins = $this->getDoctrine()->getRepository(Origin::class)->getAll();
$result = [];
foreach ($origins as $element) {
$result[$element[$element->getId()]][] = $element;
}
return $result;
问候,
看了所有的答案后,我是这样做的:
$allEntities = $this->repository->findWithOriginSortByProduct();
$entitiesByProductAndStore = [];
foreach ($allEntities as $entity) {
$key = $entity->getId();
$entitiesByProductAndStore [$key][] = $entity;
}
/**
* @return Entity[]
*/
public function findWithOriginSortByProduct(): array
{
$qb = $this->createQueryBuilder('l');
$qb
->where("l.origin != ''")
->orderBy('l.id')
;
return $qb->getQuery()->getResult();
}