希望這回答你的問題做出。我正在做類似的事情。
// Sample JSON where student has diploma.
{
"High_School": "American High School",
"HS_Diploma": true,
"HS_Diploma_date": "30-JUN-1997"
}
// Sample JSON where student does not have diploma.
{
"High_School": "American High School",
"HS_Diploma": false,
"HS_Diploma_date": null
}
$diploma = false; // Set default to false.
$diploma_date = null; // Set default data to null.
// Get Radio button 'diploma' which is set to 1 for yes.
if ($form->get("diploma")->getData() == 1){
$diploma = true; // Set boolean to true for yes.
}
if($diploma){ // If above boolean is true, student has HS diploma
$diploma_date = $form->get("diploma_date")->getData(); // So get the date.
}
// Creates a PHP array.
$high_school_array = array(
"High_School" => $form->get("high_school")->getData(),
"HS_Diploma" => $diploma,
"HS_Diploma_date" => $diploma_date->format('d-M-Y')
);
// Encode to JSON and set in Entity (here called $app), where setHSInfo() is the $app Entity
// function that takes in a string (JSON encoded).
$app->setHSInfo(json_encode($high_school_array));
// Store to database.
$em->persist($app);
$em->flush();
然後在一個控制器,從數據庫得到的,你需要解碼的JSON,然後傳遞給 您的嫩枝文件,你可以輕鬆使用它:
// Where getAppHSInfo function returns the $high_school_array encoded array above from the db.
return $this->render('viewHSDetails.html.twig', array(
'hs_json' => json_decode($app->getAppHSInfo(), true),
));
然後在枝條文件,你可以方便地使用它:
Education Information:<br/>
High School attended: {{ hs_json['High_School'] }}<br/>
{% if hs_json['HS_Diploma'] %}
Diploma Yes - Date: {{ hs_json['HS_Diploma_date'] }}
{% else %}
Diploma No
{% endif %}
您可以用'json_encode()'用JSON編碼數組(我假設,因爲PHP其你使用的標籤)。 http://php.net/manual/en/function.json-encode.php – Kisaragi
這就是你如何使用樹枝製作數組,我也需要幫助。 – UnknownPerson
嗯,我看我想。你想要一個數組?你在循環數據嗎?你想解析文本嗎?這太模糊了。 – Kisaragi