RE: [PHP] mysql_fetch_array to associative array
| From: | Robert Cummings | Date: | Tue, 17 Jul 2007 01:11:41 +0000 |
| Subject: | RE: [PHP] mysql_fetch_array to associative array | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-258966@lists.php.net to get a copy of this message | ||
On Mon, 2007-07-16 at 13:37 -0700, Andras Kende wrote:
>
> > function GetAssoc($query) {
> > $get = $this->Execute ( $query );
> >
> $result = array();
> > while ( $row = mysql_fetch_array($get) ) {
> $result[] = $row;
> >
> > }
> > mysql_free_result($get);
> >
> > return $result;
> > }
I'll focus on the above one since that's probably what's causing your
grief... I'm also going to rename it so it's more explanatory:
<?php
function GetPairs( $query, $keyField, $valueField )
{
$pairs = array();
if( ($get = $this->Execute ( $query )) )
{
while( ($row = mysql_fetch_assoc( $get )) )
{
$pairs[$row[$keyField]] = $row[$valueField];
}
mysql_free_result( $get );
}
return $pairs;
}
?>
That's the function... it creates an array of pair mappings based on the
table fields $keyField and $valueField. So let's say you have the
following table in your database:
CREATE TABLE cars
(
id int not null auto_increment,
name varchar( 32 ) not null,
primary key( id )
);
Then you might issue the following function call:
<?php
$query = "SELECT id, name FROM cars ORDER BY name ASC ";
$pairs = GetPairs( $query, 'id', 'name' );
?>
Cheers,
Rob.
--
...........................................................
SwarmBuy.com - http://www.swarmbuy.com
Leveraging the buying power of the masses!
...........................................................