如何在php中存储数组中的数据?

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

我需要为每个$ sub_val获取所有$ post,但是问题是foreach中的每个$ post被压碎了,而我仅得到最后一个。 $

print_r($postcats)的结果是

Array ( [0] => Array ( [post_id] => 6 ) 
        [1] => Array ( [post_id] => 7 ) )

[print_r($para)的结果为

Array ( [id] => 6 ) 
Array ( [id] => 7 )
$em = $this->getDoctrine()->getManager();

$repository = $em->getRepository('SiteBundle:Post');
$postcats = $repository->createQueryBuilder('t')
                    ->select('t.id as post_id')
                    ->innerJoin('t.categories', 'c')
                    ->where('c.id = :category_id')
                    ->setParameter('category_id', $getidCat)
                    ->getQuery()
                    ->getResult();


foreach ($postcats as $key => $value) { 
    foreach ($value as $sub_key => $sub_val) { 
        $entitymanager=$this->getDoctrine()->getManager();
        $para=array('id'=>$sub_val);
        print_r($para);
        $posts=$entitymanager->getRepository('SiteBundle:Post')
                            ->findBy($para);
    } 
}
return $this->render('post/index.html.twig', array(
            'posts' => $posts,
            'login' =>$usersesssion,
            )
        );
php multidimensional-array foreach repository symfony-3.4
2个回答
0
投票

[我找到了解决方案,我只是修改了我的控制器和index.html.twig的代码,为之循环了

    {   $session=$request->getSession();

        $usersesssion=$session->get('login');
        $getidCat=$category->getId();
    if($getidCat!=null){
        $em = $this->getDoctrine()->getManager();

        $repository = $em->getRepository('SiteBundle:Post');
        $postcats = $repository->createQueryBuilder('t')
                            ->select('t.id as post_id')
                            ->innerJoin('t.categories', 'c')
                            ->where('c.id = :category_id')
                            ->setParameter('category_id', $getidCat)
                            ->getQuery()
                            ->getResult(); 

        $posts= $em->getRepository('SiteBundle:Post')->findAll();
        return $this->render('post/index.html.twig', array(
        'posts' => $posts,
        'login' =>$usersesssion,
        'postcats' =>$postcats,
        ));
    }else{
        echo 'ko';
        $postcats=null;
        $em = $this->getDoctrine()->getManager();
        $posts= $em->getRepository('SiteBundle:Post')->findAll();
        return $this->render('post/index.html.twig', array(
        'posts' => $posts,
        'login' =>$usersesssion,
        'postcats' =>$postcats,
        ));
    }}


0
投票
  • 以及我的index.html.twig *
       {% for post in posts %}
       {% for postc in postcats %}
       {%if postc.post_id == post.id %}

           {% endif %}
            {% endfor %}
            {% endfor %}```

© www.soinside.com 2019 - 2024. All rights reserved.