Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Jul 2008
    Thanked 0 Times in 0 Posts

    Create variable value from database column where another column equals...

    I am sure this should be straight forward but I can't do it!!

    I have a database with a number of columns.
    One column is called ID and another column is called UN.
    I want to create an array of all the UN's with the value being the value of the ID column.

    ID UN
    1 8043
    2 8011
    3 8044
    4 8065

    I want to create something along the lines of
    $array['8043'] //value should be 1
    $array['8011'] // value should be 2

    This is what I am trying:
    $query = "SELECT id,un FROM tablename "; 
    $result = mysql_query($query); 
    $data_array = array();
    while ($row = mysql_fetch_assoc($result)) {
        $data_array[$row['un']] = $row['id'];
    print $data_array[$row['8043']];
    print $row['8043'];
    Last edited by robbiez; 03-31-2014 at 11:27 AM. Reason: Problem Resolved

  2. #2
    New Coder
    Join Date
    Jul 2008
    Thanked 0 Times in 0 Posts
    Problem became obvious when I looked again so no need for any advise.


  3. #3
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Saskatoon, Saskatchewan
    Thanked 2,668 Times in 2,637 Posts
    Yep, just a little too much info on the dereference, the $row['8043'] doesn't exist by itself rather just the 8043.
    Note though that the key => value order doesn't typically matter so long as both are unique. If both are unique, the pair can be swapped at any time (see array_flip), or you can search for keys using array_search. I personally like using the associative index, but I will only do so when its logical that the collection is a hash type. Numerically, I wouldn't swap them since I'd treat it as a flat array. That may just be me though :P
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts