0

I have the following PHP Array:

$mod = array( 1 => array(), 2 => array(), 3 => array());

When I json_encode $mod, it produces this:

{"1":[],"2":[],"3":[]}

But I want to be able to do this in the following manner:

$tstarray = array();
$newaray = array(1 => array());
$newaray2 = array(2 => array());
$newaray3 = array(3 => array());
array_push($tstarray, $newaray);
array_push($tstarray, $newaray2);
array_push($tstarray, $newaray3);

When I json_encode $tstarray, it produces a result like this:

[{"1":[]},{"2":[]},{"3":[]}]

I want the second result to look like the first result. By "look" I mean the same type. Do you know what I would need to change in order to get this to be the same?

Update: What end result do I need?

If I have var x = 9 Then I need a while loop that will create the $mod variable but do it all the way from 1 => array() to 9 => array(). How would I do this?

1 Answer 1

3
$arr1 = array(1 => array());
$arr2 = array(2 => array());
$arr3 = array(3 => array());
$arr = $arr1 + $arr2 + $arr3;

print_r(json_encode($arr));

Output is:

{"1":[],"2":[],"3":[]}

This also works with nested arrays.

$arr1 = array(1 => array(1 => "A", 2 => "B"));
$arr2 = array(2 => array(1, 2, 3));
$arr3 = array(3 => array(1 => "C", 2 => "D"));
$arr = $arr1 + $arr2 + $arr3;
print_r(json_encode($arr));

Output:

{"1":{"1":"A","2":"B"},"2":[1,2,3],"3":{"1":"C","2":"D"}}

The problems appear once you start defining zero-indexed values in your arrays... at that point they will start getting json-encoded as true arrays.

REQUEST UPDATE

$arr = array();

for ($i = 1; $i < 10; ++$i)
    $arr = $arr + array($i => array());

print_r(json_encode($arr));

Output:

{"1":[],"2":[],"3":[],"4":[],"5":[],"6":[],"7":[],"8":[],"9":[]}
Sign up to request clarification or add additional context in comments.

5 Comments

Will it also function as an array within an array?
Anyway yes, it works... but as long as you don't zero-index your arrays, otherwise they will be json-encoded as true arrays.
Make some tests as I did, for the moment I obtained a 100% behavior match.
I am new to PHP, so instead of print_r if I use echo, will it be the same?
Absolutely: echo(json_encode($arr)) prints the same... but never base your assumption on what you print... but on the content.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.