0

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

1
  • Doing $arr_brand[] = "something" appends "somrthing to the array. You probably wanted reassignment $arr_brand = "something" . Commented Feb 4, 2015 at 1:48

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.