Reputation: 45
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?
Upvotes: 0
Views: 264
Reputation: 23675
$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":[]}
Upvotes: 3