first of all, its no so easy as i sounds. lets say i have this database name - address - tel -------------------- cartman - southpark north - 111 stan - southpark east - 222 kyle - southpark west - 333 kenny - south park - 000 now i need 1 array that contains each col(!) as an array inside, starting with the col name as first value. at the end it should look like $res = array ( array('name', 'cartman', 'stan', ...) array('address', 'southpark north', 'southpark east', ...) array('tel', '111', '222', ...) ) is it possible to build such a function that can create such an array from every valid sql query?
you mean you want a function to put your entire database into an array ? perhaps if you paste the sort of sql query you want to make that structure from it'll be easier to understand.
You need to loop through those fields 3 times, and you need 4 arrays, first loop you save the names, second you save the address and so on. This is an awful way of saving database records into an array though.
If the cols names are the ones you want to put as the first element of the array, you could do something like this: <?php $query = 'SELECT name, address, tel FROM table'; $result = mysql_query($query); while ($row = mysql_fetch_assoc($result)) { foreach ($row as $column => $value) { $array_name = $column; $$array_name[0] = $column; $$array_name[] = $value; } } ?> PHP: Beware, totally UNTESTED!! Anyway, hope it helps a bit...
thanks everyone. krakjoe: no, i only need the result of 1 query in an array, not the whole database picouli: didnt work, but gave me a push into the right direction. what exactly are you trying to do if you use "$$" at $$array_name[]? i know its valid php, but i dont know what happens if yo do this...? however, here is the solution i came up with: function sql2array($sql) { global $db; $data = array(); $x = 0; $y = 1; $res = $db->query($sql); while ($row = $db->getdata($res)) { $x=0; foreach ($row as $col => $value) { $data[$x][0] = $col; echo $x."-".$y."::".$col." % ".$value."<br>"; $data[$x][$y] = $value; $x++; } $y++; } return $data; } Code (markup): you see what happens. (use mysql_query and mysql_fetch_array($your_handle, MYSQL_ASSOC) instead of my $db class) i show you something VERY COOL you can do with this function and your querys in 14 hours or so when im back from work
here is what i did with it: http://forums.digitalpoint.com/showthread.php?t=246225 wohoo, is this great or what
Using $$ is a way of creating a variable with the name of the value of the other variable. So $$random will create a variable whos name is $(whatever the value of $random is).