Reputation: 1607
I am having trouble on formatting my json. Basically I have this script structure,
$array1 = array();
for($i = 0; $i < 2 ; $i++)
{
$array1[] = array
(
"stocks" => array
(
"0" => "apple"
"1" => "banana"
"2" => "mango"
)
);
}
When executed, this outputs (in JSON format):
{
stocks:
{
0 : apple,
1 : banana,
2 : mango
}
}
{
stocks:
{
0 : apple,
1 : banana,
2 : mango
}
}
My problem is, what changes do I have to make to produce an output like this:
{
stocks:
{
0 : apple,
1 : banana,
2 : mango
},
stocks:
{
0 : apple,
1 : banana,
2 : mango
}
}
Upvotes: 0
Views: 224
Reputation: 3550
I think the easiest format would be the following:
$array1 = array();
for($i = 0; $i < 2 ; $i++)
{
$array1['stocks'][] = array
(
"0" => "apple"
"1" => "banana"
"2" => "mango"
);
}
which will display output like:
{
stocks: [
{
0 : apple,
1 : banana,
2 : mango
},
{
0 : apple,
1 : banana,
2 : mango
}
]
}
Upvotes: 5
Reputation: 9094
Your array keys has to be unique. If they're not, the values of the current item will get overwritten each iteration within the for loop.
$arr = array();
for ($i = 0; $i < 2 ; $i++) {
$arr["stocks{$i}"] = array(
"0" => "apple"
"1" => "banana"
"2" => "mango"
);
}
Upvotes: 1
Reputation: 54729
You can't have two elements in an array (or object) that have the same key. If you want to have them both in one array, you'll have to assign separate keys to each of them, like this:
$array1 = array();
for($i = 0; $i < 2 ; $i++)
{
$array1["stocks{$i}"] = array
(
"0" => "apple"
"1" => "banana"
"2" => "mango"
);
}
Which would output:
{
stocks0:
{
0 : apple,
1 : banana,
2 : mango
},
stocks1:
{
0 : apple,
1 : banana,
2 : mango
}
}
Upvotes: 1