dqq22391
2015-01-21 13:21
浏览 59
已采纳

转换Symfony2 PHP实体对象以在Javascript中使用

I'm attempting to open up data from a PHP Object (as shown below) but I'd like to be able to access this data within JavaScript to use in a graphing library.

Object in question:

http://puu.sh/eP3QZ/e4289eb0d8.png

What I need to be able to do is convert that into a JSON encoded object for use within Javascript.

I tried using twig within Symfony to do this via:

{% set playerStats = match.getStatsPlayers().getValues() }%
{% dump(playerStats) %} // This is what you see above

var playerStats = {{ playerStats|json_encode }};

console.log(playerStats);

The console shows this:

http://puu.sh/eP4aX/adf6c9978f.png

Which is where I'm banging my head against the wall. Where can I access the values of these properties?

As an inefficient way, I've managed to get it into a JavaScript object by doing:

{% for p in playerStats %}
    playerStats.push({ 'id': {{p.playerID}}, 'playerName': '{{p.playerName}}', 'playerOutfit': {{p.playerOutfit}}, 'playerFaction': {{p.playerFaction}}, 'playerKills': {{p.playerKills}}, 'playerDeaths': {{p.playerDeaths}}, 'playerTeamKills': {{p.playerTeamKills}}, 'playerSuicides': {{p.playerSuicides}} });
{% endfor %}

I feel kinda dirty for doing that. There must be a better way to do this surely?

Thanks in advance!

图片转代码服务由CSDN问答提供 功能建议

我正在尝试从PHP对象中打开数据(如下所示)但我想成为 能够在JavaScript中访问此数据以在图形库中使用。

有问题的对象:

我需要做的是转换 在Javascript中使用JSON编码对象。

我尝试在Symfony中使用twig通过以下方式执行此操作:

  {%set  playerStats = match.getStatsPlayers()。getValues()}%
 {%dump(playerStats)%} //这就是你在上面看到的
 
var playerStats = {{playerStats | json_encode}}; 
 
console。  log(playerStats); 
   
 
 

控制台显示:

这就是我撞到墙上的地方 。 我在哪里可以访问这些属性的值?

作为一种效率低下的方式,我设法通过执行以下操作将其转换为JavaScript对象:

  {%for player in playerStats%} 
 playerStats.push({'id':{{p.playerID}},'playerName':'{{p.playerName}}  ','playerOutfit':{{p.playerOutfit}},'playerFaction':{{p.playerFaction}},'playerKills':{{p.playerKills}},'playerDeaths':{{p.playerDeaths}},  'playerTeamKills':{{p.playerTeamKills}},'playerSuicides':{{p.playerSuicides}}}); 
 {%endfor%} 
   
 
 

这样做我觉得有点脏。 必须有更好的方法来做到这一点吗?

提前致谢!

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题