使用简单的JSON数组创建Doctrine查询结果

时间:2015-05-04 09:58:54

标签: php arrays json multidimensional-array doctrine-orm

在我的数据库中,我有一个名为Graphique的实体。这个架构为:

class Graphique
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var decimal
     *
     * @ORM\Column(name="index", type="decimal", precision=9, scale=3, nullable=false)
     */
    private $index;

    /**
     * @var datetime
     *
     * @ORM\Column(name="date", type="datetime", nullable=false)
     */
    private $date;

    /*getters and setters*/

这是索引的一些值,根据我的数据库架构(示例):

----------------------------------
id    | index    | dateTime      |
----------------------------------
1     | 1700.000 | dateTime datas|
----------------------------------
2     | 1200.000 | dateTime datas|
----------------------------------
3     | 1200.000 | dateTime datas|
----------------------------------
4     | 1304.000 | dateTime datas|
----------------------------------
etc...| etc...   | etc...        |

我把这个方法放到控制器中:

$em=$this->getDoctrine()->getManager();


$queryIndex = $em->createQuery( 'SELECT g.index
                                    FROM MySpaceMyBundle:Graphique g');

$array = array_map('current', $queryIndex);

$response = new Response();
$data = json_encode($array);
$response->headers->set('Content-Type', 'application/json');
$response->setContent($data);

return $response;

它将我这个回到我的json回复中:

["1700.000","1200.000","1200.000","1304.000","1800.000","2012.000","2048.000","1048.000","3000.000","5421.000"]

但是我需要有这个简单的数组结果(而不是上面给出的json响应):

[1700.000,1200.000,1200.000,1304.000,1800.000,2012.000,2048.000,1048.000,3000.000,5421.000]

我需要在json响应中返回一个简单数组,以便将这些十进制值显示为高图图形。

我该怎么办?我已经尝试了一些Doctrine方法,例如->getArrayresult()->getScalarResult()->toArray(),但结果是一样的。我需要将查询结果设置为一个简单的数组。

1 个答案:

答案 0 :(得分:2)

class Class
     def attr_validated(*args)
    args.each do |arg|
      # getter
      self.class_eval("def #{arg};@#{arg};end")
      # setter
      self.class_eval("def #{arg}=(val);@#{arg}=val;end")
    end
  end
end

class Dog
  attr_validated :num_legs ## Instead of this i need to validate a block also attr_validated :num_legs do |v|
v <= 4
end

dog = Dog.new
p dog.num_legs
p dog.num_legs = 'Stack'

此解决方案可以为您提供帮助。