从学说中获取多维数组

问题描述 投票:0回答:3

我有一张这样的桌子:

id //不是索引 起源
1 德国
1 美国
2 美国
2

我想让每个实体女巫都有一个起源(!=''),但是在一个多维数组中,按id排序,看起来像这样:

[
 [
  {
   'id': '1',
   'origin': 'germany'
  },
  {
   'id': '1',
   'origin': 'usa'
  },
 ],
 [
  {
   'id': '2',
   'origin': 'usa'
  }
 ]
]

这甚至可以通过查询实现吗?还是我必须在 PHP 中执行此操作?

php mysql symfony doctrine
3个回答
2
投票

您可以在存储库中使用 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;

问候,


1
投票

您可以像这样删除 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);

结果:

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
        )

)

0
投票

查看所有答案后,我这样做了:

$allEntities = $this->repository->findWithOriginSortById();

$entitiesByid = [];
foreach ($allEntities as $entity) {
    $key = $entity->getId();
    $entitiesByid[$key][] = $entity;
}

/**
 * @return Entity[]
 */
public function findWithOriginSortById(): array
{
    $qb = $this->createQueryBuilder('l');
    $qb
        ->where("l.origin != ''")
        ->orderBy('l.id')
    ;

    return $qb->getQuery()->getResult();
}
© www.soinside.com 2019 - 2024. All rights reserved.