How do I name an array key with a key inside the array
- by Confused
I have some data, yes, data. This data came from a MySQL query and it will always contain 4 items, always. I want to cache that data in an array table for use later within a web page but I want to keep the keys from the query and separate out each grouping within a multidimensional array. However to save time iterating through the array each time I want to find a given group of data, I want to call the keys of the first array the same as the ID key which is always the first key within each four items.
At the minute I'm using this code:
function mysql_fetch_full_result_array($result)
{
$table_result=array();
$r=0;
while($row = mysql_fetch_assoc($result)){
$arr_row=array();
$c=0;
while ($c < mysql_num_fields($result)) {
$col = mysql_fetch_field($result, $c);
$arr_row[$col -> name] = $row[$col -> name];
$c++;
}
$table_result[$r] = $arr_row;
$r++;
}
return $table_result;
}
I'm currently testing this using 3 unique users, so I'm getting three rows back from the query and the data from this function ends up in the format:
[0]=>
. . [id] => 1
. . [name] => random name
. . [tel] => random tel
. . [post] => post code data
[1]=>
. . [id] => 34
. . [name] => random name
. . [tel] => random tel
. . [post] => post code data
[2]=>
. . [id] => 56
. . [name] => random name
. . [tel] => random tel
. . [post] => post code data
So how do I alter the code to instead of the keys [0], [1], [2] give me the output:
[1]=>
. . [id] => 1
. . [name] => random name
. . [tel] => random tel
. . [post] => post code data
[34]=>
. . [id] => 34
. . [name] => random name
. . [tel] => random tel
. . [post] => post code data
[56]=>
. . [id] => 56
. . [name] => random name
. . [tel] => random tel
. . [post] => post code data
I don't mind if the main array keys are strings of numbers rather than numbers but I'm a bit stuck, I tried changing the $table_result[$r] = $arr_row; part to read $table_result[$result['id']] = $arr_row; but that just outputs an array of one person. I know I need another loop but I'm struggling to work out how to write it.