Jony Kale
Jony Kale

Reputation: 979

PHP JSON can't echo values, always returning an array?

I have started messing around with Json, with ajax recently.

I have this javascript code:

var json = {
    "test": [{
        "number":1,
        "char":"hey",
        "bool":true
    }]
};
$.ajax({
    url: "json.php",
    type: "POST",
    contentType: "application/json",
    data: {json: JSON.stringify(json)},
    success: function(res) {
        $("#box").html(res);
    }
});

A few minutes ago, this code worked absolutely fine, when I did echo $json['test']['number']; it returned 1.

But now this won't work at all, it says that 'json' index is UNDEFINED , therefore I tried using contentType: "application/x-www-form-urlencoded", which does work, but I can't get the array items at all.

If I won't pass a true parameter in the json_decode() function, I will receive the following error:

Cannot use object of type stdClass as array

If I will do it I will not get the data, but the response will say "Array".

And that's what I am echoing:

$json = $_POST['json'];
$json = json_decode($json, true);
echo $json['test'][0];

And that is my var_dump of $json:

array(1) {
  ["test"]=>
  array(1) {
    [0]=>
    array(3) {
      ["number"]=>
      int(1)
      ["char"]=>
      string(3) "hey"
      ["bool"]=>
      bool(true)
    }
  }
}

Why is it doing that? why can't I get the values out of it without it returning an Array?

Upvotes: 0

Views: 1555

Answers (1)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107498

Given this:

var json = {
    "test": [{
        "number":1,
        "char":"hey",
        "bool":true
    }]
};

Your PHP code

$json['test']['number'];

would have only worked in the first place if test was not an array. The above, in JavaScript, would look like:

json.test.number;

But test is an Array; it has no number property. In JavaScript, this would be the correct way to find the number:

json.test[0].number;

You need to do the same in PHP:

$json['test'][0]['number'];

Upvotes: 4

Related Questions