Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/264.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过Ajax在Javascript到PHP之间保持真正的数组对象?_Php_Javascript_Ajax_Arrays_Json - Fatal编程技术网

通过Ajax在Javascript到PHP之间保持真正的数组对象?

通过Ajax在Javascript到PHP之间保持真正的数组对象?,php,javascript,ajax,arrays,json,Php,Javascript,Ajax,Arrays,Json,我想通过Ajax将Javascript数组对象发布到PHP。然后在PHP端,我仍然希望将该对象用作真正的数组。下面是我的方法,到目前为止,在PHP端将传入对象用作数组方面仍然不成功。我可以将其解析为字符串 Javascript: var myObj = { fred: { apples: 2, oranges: 4, bananas: 7, melons: 0 }, mary: { apples: 0, oranges: 10, bananas: 0, melons: 0 }

我想通过Ajax将Javascript数组对象发布到PHP。然后在PHP端,我仍然希望将该对象用作真正的数组。下面是我的方法,到目前为止,在PHP端将传入对象用作
数组方面仍然不成功。我可以将其解析为
字符串

Javascript:

var myObj = { 
    fred: { apples: 2, oranges: 4, bananas: 7, melons: 0 }, 
    mary: { apples: 0, oranges: 10, bananas: 0, melons: 0 }, 
    sarah: { apples: 0, oranges: 0, bananas: 0, melons: 5 } 
}
然后,通过AJAX发送Javascript/JQuery:

$.ajax({
    type: "POST",
    url: "ajax.php",
    dataType: "JSON",
    data: { "data" : JSON.stringify(myObj) }
}).success(function( response ) {
    alert(response);
});
然后在PHP上解析:

$data = json_decode( $_POST["data"] );
echo json_encode( $data["fred"] );
echo json_encode( $data["fred"]["apples"] );
echo json_encode( $data["fred"]->apples );
echo json_encode( $data[1] );
  • 上述任何一个
    echo
    返回空白,返回浏览器
但当我:

$data = json_decode( $_POST["data"] );
$to_string = print_r( $data, true ); //<-- Used these instead
echo json_encode( $to_string ); //<-- Used these instead
  • 数据似乎在那里,但我如何才能在
    PHP
    末尾以正确的真正
    ARRAY
    方式解析这些数据呢

true
作为参数传递给json\u decode,以返回关联数组而不是对象:

json_decode($string, true);

将第二个参数传递为
true
,它将转换数组中的数据

$data = json_decode( $_POST["data"] , true);
$data = json_decode( $_POST["data"] , true);