RE: mysql_fetch_array to associative array

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 




-----Original Message-----
From: Robert Cummings [mailto:robert@xxxxxxxxxxxxx] 
Sent: Monday, July 16, 2007 6:12 PM
To: Andras Kende
Cc: php-general@xxxxxxxxxxxxx
Subject: RE:  mysql_fetch_array to associative array

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!
...........................................................

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php





Rob,

THANKS !!!!

I also hacked together a version:

while ( $row = mysql_fetch_array($get) ) {
	$result[$row[0]] = $row[1];
	}



Best regards,

Andras 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux