我有一个包含用户的表,每个用户都有一个城市。 我使用enter image description here来显示每个城市的用户数量
这是我的代码
$em = $this->getDoctrine()->getManager();
$classes = $em->getRepository('MyBundle:User')->findAll();
$data= array();
$stat=array();
foreach($classes as $class) {
$query = $em->createQuery("SELECT COUNT(u) FROM MyBundle:User u WHERE u.city = ?1");
$query->setParameter(1, $class->getCity());
if (!in_array($class->getCity(), $stat)) {
array_push($stat,$class->getCity(),($query->getSingleScalarResult() *1)/1);
}
}
array_push($data,$stat);
我只获得了第一个城市的用户数量,所以看起来我的foreach
循环效果不佳..任何帮助都将不胜感激!
答案 0 :(得分:0)
这是我的工作代码,以防有人需要它:
$em = $this->getDoctrine()->getManager();
$classes = $em->getRepository('MyBundle:User')->findAll();
$data= array();
$stat=array();
$hm=array();
$query = $em->createQuery("SELECT COUNT(u) FROM MyBundle:User u WHERE u.city = ?1");
foreach($classes as $class) {
$query->setParameter(1, $class->getCity());
if (!in_array($class->getCity(), $hm)) {
unset($stat);
$stat = array();
array_push($stat, $class->getCity(), (int)$query->getSingleScalarResult());
array_push($hm, $class->getCity());
array_push($data,$stat);
}
}