Dennis
Dennis

Reputation: 309

PHP & JSON: Inserting an array in a nested array

I am creating a JSON structure to be passed back to Ajax. I would like to insert 'para' => "Hello" into "content" like this:

{
    "sections": {
        "content": [{
            "para": "Hello"
        }]
    }
}

I tried using this code:

$array = array('sections' => array());
array_push($array["sections"], array("content" => array())); // content must be initialized as empty
array_push($array["sections"][0], array("para" => "Hello"));

But I received this instead:

{
    "sections": [{
        "content": [],
        "0": {
            "para": "Hello"
        }
    }]
}

If I try array_push($array["sections"]["content"], array("para" => "Hello")), I get an error instead. How do I insert an array into "content"? What am I doing wrong?

Upvotes: 1

Views: 999

Answers (2)

Leo Bedrosian
Leo Bedrosian

Reputation: 3799

If I understood your intentions correctly, here's the array structure you're aiming for:

array("sections" => array(
    "content" => array("para" => "Hello"),
));

However, in Javascript [] represents an array and {} represents an object. If you're trying to create an object with a property of "0", that's not possible in PHP. Variable names have to start with a letter or underscore.

Here's an array of content objects:

$content = new stdClass();
$content->para = 'hello';

array("sections" => array(
    "content" => array($content),
));

To add arrays of contents:

array("sections" => array(
    "content" => array(
        array("para" => "Hello"),
        array("para" => "Hello"),
        array("para" => "Hello"),
    ),
));

You can also construct your own contents array first if you're iterating over an index and then json_encode it. Basic example:

$content = array();

for (i=0; i <3; i++) {
    $content[] = array('para' => 'hello');
}

json_encode(array("sections" => array(
    "content" => array($content),
)));

To convert that to JSON, put your array inside a json_encode() call.

Upvotes: 2

undefined_variable
undefined_variable

Reputation: 6228

$array['sections'] = array("content" => array(array("para" => "Hello")));
echo json_encode($array);

will give the result in desired format

Upvotes: 1

Related Questions