简体   繁体   English

从学说中获取多维数组

[英]Get multidimensional Array from doctrine

I have an table like this:我有一张这样的桌子:

id //not index id //不是索引 origin起源
1 1个 germany德国
1 1个 usa美国
2 2个 usa美国
2 2个

I want to get every Entity witch has an origin (,= '') but in a multidimensional Array, sorted by the id: looking like this:我想让每个实体女巫都有一个原点 (,= '') 但在一个多维数组中,按 id: 排序,如下所示:

[
 [
  {
   '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?这甚至可以通过查询实现,还是我必须在 PHP 中执行此操作?

You can remove the empty fields like this for ex您可以像这样删除空字段

<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
        )

)

You can use QueryBuilder in your repository to do that.您可以在存储库中使用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();
}

In your Controller:在你的控制器中:

$origins =  $this->getDoctrine()->getRepository(Origin::class)->getAll();

        $result = [];
        foreach ($origins as $element) {
            $result[$element[$element->getId()]][] = $element;
        }

       return $result;

Regards,问候,

After looking at all the answers I did it like so:查看所有答案后,我这样做了:

$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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM