简体   繁体   English

php解码json数组

[英]php decode json array

I have a php page that receives a json object from javascript page, but i was not able to decode the json in php. 我有一个从javascript页面接收json对象的php页面,但我无法解码php中的json。 How to decode the json and store in php such that $arr[0]=[1,2,34,5,2]; 如何解码json并在php中存储,以便$ arr [0] = [1,2,34,5,2]; $arr[1]=[2,1,34,5,2]; $ ARR [1] = [2,1,34,5,2]; $arr[2]=[8,1,34,5,2]; $ ARR [2] = [8,1,34,5,2]; in php ? 在PHP?

after removing "myString = JSON.stringify(myObject);"
echo $value; outputs "Array"
echo $value[0]; outputs nothing
echo $value->{"key"};  outputs nothing either

how can i actually get the array contents?

javascript: JavaScript的:

var mon=[1,2,34,5,2];
var tue=[2,1,34,5,2];
var wed=[8,1,34,5,2];
var myObject = {'key' :'value','key2':'value','key3':'value'};

myObject.key = mon;
myObject.key2 = tue;
myObject.key3 = wed;

 myString = JSON.stringify(myObject); //this line removed

var jsonString = JSON.stringify(myObject);

$.ajax({
    type: "POST",
    url: "n3.php",
    data: {data : jsonString}, 
    cache: false,

    success: function(aaa){ 
        alert("OK");

         $("#pageContent").html(aaa);       
    }
});

php: PHP:

<?php
$value = json_decode($_POST['data']);
echo $value;     //this echos the whole json object 
echo $value->{"key"};  //this outputs nothing
?>

You are JSON encoding your data twice on the Javascript side. 您是在Javascript端对JSON编码两次数据。 When you call json_encode in PHP once, you get a JSON encoded object back. 当您在PHP中调用json_encode一次时,您将获得一个JSON编码对象。 That's why echo $value outputs the whole string. 这就是echo $value输出整个字符串的原因。 If it was a PHP array at this point it would output "Array" or an error in case it was an object, it would not output the whole content. 如果此时它是一个PHP数组,它将输出“数组”或错误,如果它是一个对象,它将不会输出整个内容。

Either json_decode it again, or don't double encode it in Javascript. 要么json_decode再次编码,要么不要在Javascript中对其进行双重编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM