Reputation: 728
I'm trying to generate json from a mysql statement using the following code:
while($row = mysqli_fetch_array($r))
{
$arr_brand[] = array('ID' => $row['ID'],'Name' => $row['brand_name']);
$arr_brands[] = array('Brand' => $arr_brand);
}
however, This is how the JSON is coming out:
[{
Brand: [{
ID: "1",
Name: "CocaCola"
}]
}, {
Brand: [{
ID: "1",
Name: "CocaCola"
}, {
ID: "2",
Name: "Fanta"
}]
}]
As you can see it is duplicating the first row in the database. Why is this and how can I stop it?
Thanks
Upvotes: 0
Views: 26
Reputation: 91734
You will be duplicating a lot more than just the first row:
$arr_brand[] = array('ID' => $row['ID'],'Name' => $row['brand_name']);
$arr_brands[] = array('Brand' => $arr_brand);
In the first line you are adding a new element to the $arr_brand
array so that array grows with every row. Then you add that growing array to your $arr_brands
array.
So the first row of $arr_brands
will contain the first row of your database result, the second one the first two rows, the third row the first three, etc.
You probably want:
$arr_brand = array('ID' => $row['ID'],'Name' => $row['brand_name']);
$arr_brands[] = array('Brand' => $arr_brand);
Upvotes: 2