PHP Json回声特定项 [英] PHP Json echo specific item

查看:102
本文介绍了PHP Json回声特定项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从json中获取特定值,但是我无法使其正常工作. 这是我的保存格式,这些是来自输入字段的值.

i want to get the specific value from the json, but i can't get it to work. this is my save format, these are values from input fields.

               $.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);

现在我想分别回显这些值:

and now i want to echo these values seperately:

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

但这只会引发以下错误:

but this only throws me following errors:

:注意:尝试获取非对象的属性 数组:注意:未定义索引:产品

for the object: Notice: Trying to get property of non-object in for the array: Notice: Undefined index: Produkt in

这是完整的json文件:

this is the complete json file:

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

你能帮我吗?

推荐答案

您需要对json进行两次解码,因为在文件中的保存方式.试试这个:

You need to decode the json two times because the way you have it in the file. Try this:

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

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

这篇关于PHP Json回声特定项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆