Very simple array question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
rhecker
Forum Contributor
Posts: 178
Joined: Fri Jul 11, 2008 5:49 pm

Very simple array question

Post by rhecker »

I want to build an array from two values in a MySQL table. Although the code sample below doesn't work, I think it will show what I'm trying to do:

Code: Select all

$sql=mysql_query("SELECT id, label FROM table");
while ($form=mysql_fetch_array($sql)){
$labelset= array($form[id] => $form[label]);
}
echo $labelset[14];	
echo $labelset[5];
I appreciate any help.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Very simple array question

Post by AbraCadaver »

Two ways depending on what you want:

Code: Select all

// multidimensional array $labelset[0][1] = 'some label' / assume the 1 is a form id
$sql=mysql_query("SELECT id, label FROM table");
while ($form=mysql_fetch_array($sql)){
   $labelset[] = array($form['id'] => $form['label']);
}
//or 

// array $labelset[1] = 'some label' / assume the 1 is a form id
$sql=mysql_query("SELECT id, label FROM table");
while ($form=mysql_fetch_array($sql)){
   $labelset[$form['id']] = $form['label'];
}
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
rhecker
Forum Contributor
Posts: 178
Joined: Fri Jul 11, 2008 5:49 pm

Re: Very simple array question

Post by rhecker »

Thank you for both samples. The second one was exactly what I needed.
Post Reply