通过jquery发送的关联php数组返回[Object object]

I have to pass a php multidimensional array via ajax/jQuery to another php file. I have encoded the array using I expected theat every item in the array would have been an array itself. Instead it returns [Object object]. How can I access the data using php?

here's my code:

in the first php file:

<script type="text/javascript">
var arr_data = <?php echo json_encode($itemsData); ?>;
$("#confirmButton").click(function(){
    $.post("send_test.php", {"my_array_data[]":my_array_data}, function( data ) {
        alert(data);
    });
});
</script>

the other php file:

<?php
$my_array_data = $_POST['my_array_data'];
?>

if I try to retrieve the first row ($my_array_data[0]) I get [Object object] I just want to access to $my_array_data[0]['category'] etc.

A couple of errors here:

  • the data you are passing to ajax has an incorrect key using brackets[]
  • you are not passing the correct object through ajax since my_array_data is never defined

redo your code like this:

PHP

$itemsData = array(
    array(
        "test" => 30,
        "test2" => 10,
    ),
    array(
        "test" => 90,
        "test2" => 50,
    )
);

JS

var arr_data = <?php echo json_encode($itemsData); ?>;
$("#confirmButton").click(function () {
    $.post("send_test.php", {my_array_data: arr_data}, function (data) {
        console.log(data);
    });
});

Then in send_test.php

$data = $_POST['my_array_data'];
print_r($data);

Result:

Array
(
    [0] => stdClass Object
        (
            [test] => 30
            [test2] => 10
        )

    [1] => stdClass Object
        (
            [test] => 90
            [test2] => 50
        )

)

You're putting json-encoded data into the arr_data javascript variable - however you don't appear to be sending that to the other php file.

In the other php file, try using json_decode on the data you're receiving in the POST request:

$my_array_data = json_decode($_POST['my_array_data']);

Yes, as Aric says, name array consistently like this:

var my_arr_data = <?php echo json_encode($itemsData); ?>;