从 Doctrine 结果集创建关联数组的更好方法
Better way to create associative array from Doctrine resultset
我经常做这样的简单循环,将单个值从 Doctrine 结果集映射到 id->value 映射数组:
$rows = $this->em->getRepository(Tag::class)->findAll();
$result = [];
foreach ($rows as $row) {
$result[$row->getId()] = $row->getName();
}
我记得看到过一个更简单的方法的例子,可能有一个像 array_map 这样的数组函数..但我想不出来。有人有办法用更少的代码做到这一点吗?
我觉得你需要的是学说的INDEX_BY
By default a result is incremented by numerical keys starting with 0.
However with INDEX BY you can specify any other column to be the key
of your result, it really only makes sense with primary or unique
fields though
$query = $this->em->getRepository(Tag::class)
->createQueryBuilder('t')
->indexBy('t', 't.id');
$result = $query
->getQuery()
->getResult();
我经常做这样的简单循环,将单个值从 Doctrine 结果集映射到 id->value 映射数组:
$rows = $this->em->getRepository(Tag::class)->findAll();
$result = [];
foreach ($rows as $row) {
$result[$row->getId()] = $row->getName();
}
我记得看到过一个更简单的方法的例子,可能有一个像 array_map 这样的数组函数..但我想不出来。有人有办法用更少的代码做到这一点吗?
我觉得你需要的是学说的INDEX_BY
By default a result is incremented by numerical keys starting with 0. However with INDEX BY you can specify any other column to be the key of your result, it really only makes sense with primary or unique fields though
$query = $this->em->getRepository(Tag::class)
->createQueryBuilder('t')
->indexBy('t', 't.id');
$result = $query
->getQuery()
->getResult();