4

How can I make this array with data from a database?

$array=array("a"=>"Apple","b"=>"Ball","c"=>"Cat");

I have a database table with column letter and value.

letter | value
       |
  a    | Apple
  b    | Ball
  c    | Cat

I want "a"=>"Apple","b"=>"Ball","c"=>"Cat" to be values from the database, using for loop, how is that possible?

Many thanks for any help!

2
  • first question, what database? Commented Sep 13, 2011 at 7:29
  • thanks for your response @Dagon, its MySql.. Commented Sep 13, 2011 at 7:30

1 Answer 1

10

assuming you can do the connection and select

$array=array();
while ($row = mysql_fetch_assoc($result)) {
    $array[$row['letter']]=$row['value'];
}

print_r($array);
Sign up to request clarification or add additional context in comments.

2 Comments

Wow! I got the idea from your answer, thanks @Dagon! I just made a little modification based on my needs: $options=array(); foreach ($products as $key => $value){ $options[$value]=$value; }
your code does no make much sense related to the question above, your just reformatting an existing array taking the values from one to make another with matching key values pairs, which is a little pointless

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.