SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    May 2005
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Getting assoc. array from DB query

    Hi all!

    Need to get an associative array.

    Mysql table data:

    id | vendor | category
    1 | Canon | 12
    2 | Canon | 13
    3 | Canon | 19
    4 | Canon | 5
    5 | Nikon | 3
    6 | Nikon | 17

    How can I get an array such as:

    PHP Code:
    $array = array("Canon" => array(1213195)
    "Nikon" => array(317)

    Help please!

    Trying to use
    PHP Code:
    while($sql mysql_fetch_assoc($result)) {
    $array['vendor'][] = $sql;

    but getting result not needed

    PHP Code:
    echo "<pre>";
    print_r($array);
    echo 
    "</pre>"

  2. #2
    SitePoint Guru gavwvin's Avatar
    Join Date
    Nov 2004
    Location
    Cornwall, UK
    Posts
    686
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You were nearly there
    PHP Code:
    while($sql mysql_fetch_assoc($result)) {
       
    $vendor $sql['vendor'];
       
    $category $sql['category'];
       
    $array[$vendor][] = $category;

    $sql is an associative array with the names of all the columns as keys and the rows values as values.

  3. #3
    SitePoint Member
    Join Date
    May 2005
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes, thanks!
    But print_r($array) outputs result not expected:

    Array
    (
    [Canon] => Array
    (
    [0] =>
    [1] =>
    [2] =>
    [3] =>
    )
    [Nikon] => Array
    (
    [0] =>
    [1] =>
    )
    )

    I expect:

    Array
    (
    [Canon] => Array
    (
    [0] => 12
    [1] => 13
    [2] => 19
    [3] => 5
    )
    [Nikon] => Array
    (
    [0] => 3
    [1] => 17
    )
    )

    What's wrong?

  4. #4
    SitePoint Member
    Join Date
    May 2005
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Works!
    I was mistaken in naming an array, not correct field name was there


Bookmarks

Posting Permissions

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