MySQL Query into a 2D Array

Discussion in 'PHP' started by wvccboy, Nov 6, 2013.

  1. #1
    I need to take a query from a MySQL database and place it into a multi-dimensional array dynamically, but I am having a difficult time understanding how to write the query properly.

    The end result for my array looks like this:

    $result['Employee1']['Item1'] = 'A1';
    $result['Employee1']['Item2'] = 'A2';
    $result['Employee2']['Item1'] = 'B1';
    $result['Employee2']['Item2'] = 'E1';
    
    PHP:
    As shown in the above, I am querying an employee, an item, and the string associated with each part of the array.

    What I am wondering is: what could my generic query look like (also if the data is stored in more than one table, would a join be sufficient?), and what code would I need in order to produce the same as above using a while or foreach loop instead of typing it manually?

    Thank you for the help.
     
    Solved! View solution.
    wvccboy, Nov 6, 2013 IP
  2. #2
    Lets say your query was
    select employee_id, product_id
    
    from sales
    Code (markup):
    see how that works in a fiddle: http://sqlfiddle.com/#!2/27133/1

    then your php would be

    $output = array();
    foreach($result as $val) $output[$val['employee_id'][] = $val['product_id'];
    
    //the var_dump should show what you are looking for
    var_dump($output);
    PHP:
     
    sarahk, Nov 6, 2013 IP
    ryan_uk likes this.
  3. wvccboy

    wvccboy Notable Member

    Messages:
    2,632
    Likes Received:
    81
    Best Answers:
    1
    Trophy Points:
    250
    #3
    Thank you for the help!

    I ended up assigning the variables to $output based on the values I received from the database and running foreach() loops on $output.
     
    wvccboy, Nov 8, 2013 IP