Creating an array of associative arrays in PHP I am fetching rows from the DB and returning the result in JSON. The output needs to be an array of associative arrays.

$i = 0;
foreach($resultSet as $r)
{
  $output[$i]['key1'] = $r['col1'];
  $output[$i]['key2'] = $r['col2'];
  ...
  $output[$i]['keyN'] = $r['colN'];
  $i++;
}


Is there a more elegant way to do this? Is there anything wrong with this approach? If yes, what is it?
Instead of declaring $i=0; before the loop, you can also write :

foreach($resultSet as $i =&gt; $r)
{
  $output[$i]['key1'] = $r['col1'];
  $output[$i]['key2'] = $r['col2'];
  ...
  $output[$i]['keyN'] = $r['colN'];
}


Also, if you could rename your column in the DB query, you could have :

foreach($resultSet as $i =&gt; $r)
{
  $output[$i] = $r;
}


Which is pretty much like doing $output = $resultSet;

Edit :
If you do need to do some processing on $resultSet for whatever reason and you'd rather have different names, you can consider doing :

for (array('key1' =&gt; 'col1', ... 'keyN' =&gt; 'colN' as key =&gt; col)
{
   $output[$i][$key] = $r[$col];
}