我需要摆脱我的JSON字符串中的双引号,这就是我如何形成一个数组然后将其转换为JSON
$dinnerDetails = array();
foreach ($dinners as $dinner) {
$dinnerDetails[] = array(
"title" => $dinner->getName(),
"data" => $dinner->getDate()
);
}
$dinnerDetails = json_encode($dinnerDetails);
当我转储$dinnerDetails
时,在我的视图中,我看到以下内容
string '[
{
"title": "Formal Dinner",
"data": "Tue Apr 05 2016 05:00:00 GMT+0500 (PKT)"
},
{
"title": "Formal Dinner",
"data": "Tue Apr 05 2016 05:00:00 GMT+0500 (PKT)"
},
{
"title": "Black Tie",
"data": "Wed Apr 13 2016 05:00:00 GMT+0500 (PKT)"
},
{
"title": "Formal Dinner",
"data": "Fri Apr 08 2016 05:00:00 GMT+0500 (PKT)"
}
]
当我将此分配给JS变量时,这是在源
中看到它的方式var dinners = [
{
"title": "Formal Dinner",
"data": "Tue Apr 05 2016 05:00:00 GMT+0500 (PKT)"
},
{
"title": "Formal Dinner",
"data": "Tue Apr 05 2016 05:00:00 GMT+0500 (PKT)"
},
{
"title": "Black Tie",
"data": "Wed Apr 13 2016 05:00:00 GMT+0500 (PKT)"
},
{
"title": "Formal Dinner",
"data": "Fri Apr 08 2016 05:00:00 GMT+0500 (PKT)"
},
{
"title": "Formal Dinner",
"data": "Sat Apr 16 2016 05:00:00 GMT+0500 (PKT)"
},
{
"title": "Formal Dinner",
"data": "Mon Mar 28 2016 05:00:00 GMT+0500 (PKT)"
}
];
我正在使用Symfony框架,这就是我将$dinnerDetails
传递给视图
return $this->render('AppBundle:admin/college:edit.html.twig', array(
'dinners' => $dinnerDetails
));
然后在内部树枝中我将像这样分配给js变量
var dinner = jQuery.parseJSON(dinners);
在JS中我甚至尝试过JSON.parse(dinners.replace(""",'"'));
,但这没有帮助。
我正在寻找的输出是这样的
[
{
title: "All Day Event",
date: "Fri Apr 08 2016 05:00:00 GMT+0500",
},
{
title: "Long Event",
date: "Fri Apr 08 2016 05:00:00 GMT+0500",
},
]
我真的很感激这里的帮助。
答案 0 :(得分:0)
在您的控制器或php文件中使用以下代码。
<?php
$arrDinnerDetails = array();
foreach ($dinners as $dinner)
{
$arrDinnerDetails[] = array(
"title" => $dinner->getName(),
"data" => $dinner->getDate()
);
}
return $this->render('AppBundle:admin/college:edit.html.twig', array(
'arrDinnerDetails' => $arrDinnerDetails
));
?>
在您的视图文件中,使用以下代码。
<script>
var strJsonDinner = JSON.stringify('<?php echo json_encode($arrDinnerDetails); ?>');
</script>
答案 1 :(得分:0)
尝试模板中的raw-filter。像这样:
{{ dinners|raw }}
第二。您已将PHP-Object序列化为JSON字符串。
如果将此字符串粘贴到脚本块中,则此字符串将解释为为JS。
它现在是JS代码,不再是字符串了。你不必解析它;实际上你无法解析它。
<script> var dinner = {{ dinners|raw }}; </script>