2017-04-06 119 views
1

我正在将Doctrine2整合到CodeIgniter中。如何将Doctrine数组转换为PHP关联数组

我的实体类News.php

<?php 

namespace Models\Entities; 

/** 
* News 
* 
* @Table(name="news", indexes={@Index(name="slug", columns={"slug"})}) 
* @Entity 
*/ 
class News { 
    //HERE: properties, getter, setter, etc. 
} 

我的模型类News_model.php

<?php 
require_once(APPPATH."models/entities/News.php"); 
use Models\Entities\News; 

class News_model extends CI_Model { 
    //Model code here 
} 

当我使用$消息= $这个 - > EM-> getRepository('实体:新闻“) - >的findAll()在News_model类和印刷,后续代码var_dump($消息),我得到的对象(模型数组\实体\新闻),就像如下:

array (size=6) 
    0 => 
    object(Models\Entities\News)[87] 
     private 'id' => int 1 
     private 'title' => string 'text here' (length=9) 
     private 'slug' => string '' (length=0) 
     private 'text' => string 'text here' (length=9) 
     private 'news' => null 
) 

但我预计的关联数组,就像如下:

array (size=6) 
    0 => 
    array (size=4) 
     'id' => string '1' (length=1) 
     'title' => string 'text here' (length=9) 
     'slug' => string '' (length=0) 
     'text' => string 'text here' (length=9) 
) 

我怎么能转换主义实体对象(第一显示阵列)导致的PHP关联数组(第二显示阵列)?

回答

2

您正在使用Doctrine ORM。 ORM意味着对象关系映射器。你使用ORM是因为你想获得结果作为对象。否则,你最好开始阅读关于Doctrine DBAL。 那么这条线:

$news = $this->em->getRepository('Entities:News')->findAll(); 

如果您使用的findAll(),那么你希望的对象的集合。在学说中,我们讨论的是collections而不是数组。

这些集合可以像普通数组一样简单地通过foreach遍历。然后你可以使用每个对象具有一定的好处的内部集合:特殊的直接调用一些自定义的方法

$newitems = $this->em->getRepository('Entities:News')->findAll(); 

foreach($newsitems as $newsitem) 
{ 
    echo '<h3>' . $newsitem->getTitle() . '</h3>'; 
} 
+0

谢谢,我适应与对象的工作的看法。 – omixam

0

我@Frank B,您使用的原则同意的理由是,你得到的对象,而不是一个工作魔法阵列。

但是,如果您设置了数组,则可以使用Symfony Serializer将任何对象转换为数组。

只是一些注释添加到您的实体:

use Symfony\Component\Serializer\Annotation\Groups; 

class News { 
    /** 
    * @Groups({"group1"}) 
    */ 
    protected $id; 

    /** 
    * @Groups({"group1"}) 
    */ 
    protected $title; 

    /** 
    * @Groups({"group1"}) 
    */ 
    protected $slug; 
} 

然后你就可以将你的数组集合是这样的:

$news = $this->em->getRepository('Entities:News')->findAll(); 
$serializer = $this->getContainer()->get('serializer'); 
$newsArray = $serializer->normalize($news, 'json', ['groups' => ['group1']]); 
1

为什么不你在分类储存使用原生主义方法getArrayResult

在你的控制器:

/***/ 
$news = $this->em->getRepository('Entities:News')->yourMethodName(); 
/***/ 

在您分类储存:

class NewsRepository extends \Doctrine\ORM\EntityRepository 
{ 
    public function yourMethodName() 
    { 
     $query = $this->createQueryBuilder('n'); 

     /***/ 

     return $query->getQuery()->getArrayResult(); 
    } 
}