Search code examples
phpjsonparsingobjectbrackets

Confusion around bracketed objects [{"a":"b"}] and non-bracketed objects {"a":"b"} in PHP


I've had an AJAX result that get's json_encode($result); in PHP before being returned.

Originally the data returned looked like this:

[{"ID":"4066","post_title":"TATTOO SLEEVES"}]

Note it has [ ] brackets!!
Then I would parseJSON the data and work with it.

data = $.parseJSON(data);

However, I need to return an extra value, so in the AJAX hook before returning I added:

$sql_search["sql_search_count"] = $sql_search_count;

Now suddenly my data gets returned like this:

{"0":{"ID":"4066","post_title":"TATTOO SLEEVES"},"sql_search_count":"1"}

No more [ ] brackets!
I'm trying to split this data; getting the "0" string part, and pushing it through a $.parseJSON(data); just like before. But I cannot seem to find out how.

Why are there sometimes [ ] brackets and sometimes not?

How do I get the "0" string in a new variable with [ ] around it?

I tried the following:

$sql_search[0]["sql_search_count"] = $sql_search_count;
but that gives me an error...

If I change it to $sql_search[0]->sql_search_count = $sql_search_count; it works.
But it is not not on the top level, it becomes a child of the first result like this:
[{"ID":"4066","post_title":"TATTOO SLEEVES","sql_search_count","1"}]


Solution

  • Do

    $sql_search[0]["sql_search_count"] = $sql_search_count;

    in your PHP code and it'll start working as before. The reason why the brackets are missing is that

    $sql_search["sql_search_count"] = $sql_search_count;

    will ask PHP to include a key called sql_search_count into $sql_search variable. Since its an array, it directly cant. It converts it into the format you're seeing now.