2017-01-30 41 views
0

我想從json獲取具體的值,但我無法讓它工作。 這是我的保存格式,這些是來自輸入字段的值。PHP Json回聲特定項目

   $.ajax({ 
       type: "POST", 
       url: "speichern.php", 
       dataType: 'json', 
       data: { 
        "Produkt": { 
         "Produktkategorie": Produktkategorie, 
         "Optionen": { 
          "MaxBreite": MaxBreite, 
          "MaxHoehe": MaxHoehe, 
          "MinBreite": MinBreite, 
          "MinHoehe": MinHoehe, 
          "ProduktStaerke": ProduktStaerke, 
          "KantenAuswahl": KantenAuswahl, },        
           "Formen": { 
            "FormRund": FormRund, 
            "FormEllipse": FormEllipse, 
            "FormHexagon": FormHexagon, 
            "FormSchnittlinks": FormSchnittlinks, 
            "FormRechtQuad": FormRechtQuad, 
           } 


        } 
       }, 
      }).done(function(msg) { 
       console.log(msg); 
      }); 

這裏被保存到文件:

$neu = json_encode($_POST); 
$file = file_get_contents('results.json'); 
$data = json_decode($file); 
unset($file); 
$data[] = $neu; 
file_put_contents('results.json',json_encode($data)); 
unset($data); 

,現在我想seperately呼應這些值:

$string = file_get_contents("results.json"); 
$jsonObject = json_decode($string); 
$jsonArray = json_decode($string, true); 
echo $jsonObject->Produkt->Produktkategorie . " and " . `$jsonArray['Produkt']['MaxBreite'];` 

但這只是拋出了我以下錯誤:

對象:注意:試圖獲取數組中的非對象屬性 :注意:未定義指數:PRODUKT在

這是完整的JSON文件:

["{\"Produkt\":{\"Produktkategorie\":\"TestArtikel\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Ecke\"},\"Formen\":{\"FormRund\":\"true\",\"FormEllipse\":\"true\",\"FormRechtQuad\":\"true\"}}}"] 

你能幫助我嗎?

+0

當你嘗試回顯時會發生什麼 print_r($ jsonObject,1); print_r($ jsonArray,1); – Ajaypayne

+0

你確定'json'實際上是保存到文件中嗎? – Ionut

+0

以下錯誤:「注意:數組到字符串轉換」 – chim

回答

0

你需要解碼json兩次,因爲你在文件中有它的方式。試試這個:

$json = file_get_contents('results.json'); 

$json = json_decode($json, true); 
$json = json_decode($json[0], true); 
echo $json['Produkt']['Produktkategorie']; 
+1

這個人是聖盃!有用!謝謝你:) – chim

+0

@chim,真棒。我很高興它的工作。樂於幫助。 – Ionut

0

只需使用

echo $jsonObject->Produkt->Produktkategorie . " and " . `$jsonArray['Produkt']['Optionen']['MaxBreite']; 
+0

我得到了同樣的錯誤:注意:未定義的索引:產品 – chim

1

取代你的最後一行。當你發佈的數據,也許你需要設置數據類型。
數據類型: 'JSON'

 $.ajax({ 
     url: 'speichern.php', 
     type: 'post', 
     dataType: 'json', 
     success: function (data) { 

     }, 
     data: {data:jsondata} 
    }); 

而在你的PHP文件,你可以得到JSON數據像以下。

$json=json_decode(stripslashes($_POST['data']), true); 

希望它可以幫助你。

+0

我將它添加到保存代碼,但沒有更改:/ – chim

+0

我編輯了答案。它可以幫助你。 –

+0

對不起,但我應該在哪裏設置新的代碼? – chim