2016-04-28 57 views
0

我需要在我的JSON字符串擺脫雙引號去掉雙引號的,這就是我正在形成一個數組,然後將其轉換成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 
)); 

,然後裏面小枝我喜歡這個

var dinner = jQuery.parseJSON(dinners);

在JS我甚至試過分配給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", 
        }, 
] 

我真的在這裏欣賞幫助。

+2

如何將'$ dinnerDetails' php變量賦值給JavaScript變量?請提供代碼 –

+0

你的意思是這樣的https://jsfiddle.net/7obbbn4n/ – AshBringer

+0

看來Symfony框架會自動處理你傳遞的所有內容,就好像它應該是html編碼一樣。這不是我熟悉的,但是你應該看看是否有另一種'render'方法,你可以告訴它'dinners'或'$ dinnerDetails'應該是JS編碼的,或者可能是未編碼的,而不是。 –

回答

0

嘗試raw-filter在您的模板中。類似這樣的:

{{ dinners|raw }} 

2nd。你已經將一個PHP對象序列化爲一個JSON字符串。
如果你將這個字符串粘貼到一個腳本塊中,這個字符串將會被解釋爲爲
現在是JS代碼,不再是字符串了。你不必解析它;實際上你不能解析它。

<script> var dinner = {{ dinners|raw }}; </script> 
+0

謝謝soooo我應該想到這:) – Saadia

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>