CMTV CMTV - 1 year ago 76
JSON Question

JSON and PHP encode multiply array

In my PHP script, I am trying to encode my multiply news array into JSON.

My news array:

$news[1]["header"] = "First header";
$news[1]["content"] = "First news content";

$news[2]["header"] = "Second header";
$news[2]["content"] = "Second news content";

I use this function to encode this array:


After that, I send this JSON data in my JS script.

var result = JSON.parse(xmlHttp.responseText); // Here is my JSON object

How can I get, for example first news header in my JavaScript code?

Thanks for any help. It is really hard for me to unserstand json syntax.

Answer Source

JSON.parse creates an object where properties (keys) are 1, 2, etc. So you can access the first header with result[1].header or result[1]['header'].

You can also access the headers by iterating over the result:

for (var index in result) {
    if (result.hasOwnProperty(index)) {

This outputs:

First header
Second header

EDIT: Here is a demo:

var json = '{"1":{"header":"First header","content":"First news content"},"2":{"header":"Second header","content":"Second news content"}}';

var result = JSON.parse(json);


for (var index in result) {
    if (result.hasOwnProperty(index)) {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download