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?
var_dump
the array actually contains what you expect. also double-check you're using the right options when callingjson_encode
. – hakre yesterdayfor
loop to process one big chunk of data before I can send anything tojson_encode
. Thus, I need a direct way to insert objects/arrays intocontent
. It is easy to insert a second dimension of arrays forsections
by writingarray_push($array['sections'], array('content' => array()))
but I have no idea how to usearray_push
for the next array dimension. – Dennis yesterdayarray_push(...)
is equal to$array[] = $valueToBePushed;
. Both do not handle array dimensions because an array first of all is flat, so there is only one dimension. however, nothing stops you to create an array inside an array which is also known as multi-dimensional array. That's why I suggested to build the content array first. This will simplify what you try to achieve. – hakre yesterday