Jump to content

Recommended Posts

Hi,

 

I have a simple task which i can seem to solve.

 

I have a table in my database like this:

 

id      fruit      color

1      apple    green

2      banana  yellow

.......

 

Now i want to create an array where to key is the id and the value is the fruit.

array(1 => apple, 2 => banana, .....)

 

How would i do this with php/mysql?

 

TIA,

 

Carlo

Link to comment
https://forums.phpfreaks.com/topic/87734-sql-table-to-array/
Share on other sites

you must of written some code ?

 

Not sure if i understand your question.

 

I am trying to create a Drupal cms module in php.

 

This is what i tried but its not correct:

 

<?php 
  $query = ("SELECT * FROM {table}");
  $result = db_query($query);
  while ($row = db_fetch_array($result)) {
    $ptype = array($row[id] => $row[type]);
  }
?>

 

Now everytime it looks it will rewrite the array so in the end it only holds the last row.

What I want is that it holds all the rows in that array so the id's are the keys and the values are the type.

 

Hope this is clearer now.

 

Carlo

 

Link to comment
https://forums.phpfreaks.com/topic/87734-sql-table-to-array/#findComment-448751
Share on other sites

your code should be

 

<?php 
  $query = ("SELECT * FROM {table}");
  $result = db_query($query);
$ptype = array();
  while ($row = db_fetch_array($result)) {
    $ptype[$row[id]] = $row[type];
  }

print_r($ptype);
?>

 

 

hope its helpful

Link to comment
https://forums.phpfreaks.com/topic/87734-sql-table-to-array/#findComment-448753
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.