2014-12-26 124 views
0

我從數據庫中提取了「form_json」,該數據庫中包含json保存的所有表單模板。代碼爲:Json字符串解碼mysql

<?php 
include ('connection.php'); 


$id = intval($_GET['frmid']); 
$results = mysqli_query($conn, "SELECT form_json FROM form WHERE form_id=$id");  
while ($row = mysqli_fetch_array($results))  
{  
$url = $row['form_json']; 
echo $url; //Outputs: 2 

} 
?> 

現在,我想解碼所有這些jsons被保存在行form_json。無論如何去遍歷或者什麼?

$json ='{"value":"Form Title","name":"title"}'; 
    var_dump(json_decode($json)); 
    var_dump(json_decode($json, true)); 

這是我們如何解碼,但這是一個字符串/一個表單模板。我可以在數據庫中保存許多json字符串/許多表單模板。我應該能夠解碼所有。

+0

不知道你在問什麼。它只是'var_dump(json_decode($ url))'? – Barmar

回答

0

你可以做的最好的事情就是將單個json字符串存儲到數組中。問題是,你的JSON字符串編碼,所以你需要先Concat的他們,如果你想一次全部結果:

$json = array(); 
$results = mysqli_query($conn, "SELECT form_json FROM form WHERE form_id=$id");  
while ($row = mysqli_fetch_array($results)) {  
    array_push($json, $row['form_json']); 
} 

$json = implode(",",$json); // concats all json strings with commas 

在這一點上,你有一個大的字符串。要進行成功解碼,你必須包裝串周圍的容器是一個有效的解析,因爲你的價值觀已經JSON,你需要爲他們的容器:

$json = '{"templates": [' . $json . ']}'; 

現在你有一個有效的JSON字符串,被解碼,無論是數組還是對象。爲了更好地理解一個簡單的工作示例:

<?php 
    $json1 = '{"value":"Form Title","name":"title"}'; 
    $json2 = '{"value":"A Message","name":"message"}'; 

    $arr = array($json1, $json2); 
    $json = implode(",", $arr); 
    $json = '{"templates": ['.$json.']}'; 
    $json = json_decode($json, true); // true if you want an array, false if you want an object 

    echo "<pre>"; 
    print_r($json); // returns a multidimensional array of all templates 
    echo "</pre>"; 
?> 
0
$json = '{"value":"Form Title","name":"title"}'; 
$data = json_decode($json); 
$value = $data->value; //will output = Form Title 
$title = $data->title; //will output = title 

我希望這會幫助