# What is the efficient way to create 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. The way I achieve this is:

$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 ? - Which DB API are you using? If PDO, your best bet will be to alias the columns to whatever you want their names to be (SELECT a as b or SELECT a b) and then use fetchAll(). Not sure what other APIs have a method like that. – Corbin Jan 7 '13 at 5:33 ## 2 Answers Instead of declaring $i=0; before the loop, you can also write :

foreach($resultSet as$i => $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 => $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' => 'col1', ... 'keyN' => 'colN' as key => col) {$output[$i][$key] = $r[$col];
}

-
The $i IS outside the loop in my actual code. I have updated the question. The reason I am not using the resultset directly is that I do some operation on the resultset array before output. But I think, I might as well think about modifying my query and do all the operatrions in the SQL itself, so that I could simply return the resultset. Isn't it ? – gentrobot Jan 7 '13 at 6:41 Oops I messed up when I copy-pasted in my editor. You can consider my first comment then. – Josay Jan 7 '13 at 6:44 I edited my post. Not sure if it would help. – Josay Jan 7 '13 at 6:49 Perhaps something like this? $i = 0;
foreach($resultSet as$key => $value){$output[$i++][$key] = $value; }  Given a $resultSet like this:

$resultSet['key0'] = 'value0';$resultSet['key1'] = 'value1';
$resultSet['key2'] = 'value2';$resultSet['key3'] = 'value3';
$resultSet['key4'] = 'value4';$resultSet['key5'] = 'value5';


The above code will produce something as follows:

Array (
[0] => Array ( [key0] => value0 )
[1] => Array ( [key1] => value1 )
[2] => Array ( [key2] => value2 )
[3] => Array ( [key3] => value3 )
[4] => Array ( [key4] => value4 )
[5] => Array ( [key5] => value5 )
)


Echoing $output[0]['key0] will output value0 (or an array if value0 is an array). As a side note, you could actually get completely rid of$i, and just do the following:

foreach($resultSet as$key => $value){$output[][$key] =$value;
}


Do let me know if I completely misunderstood the question at hand though :)

-