Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP and outputting one-to-many results
    text
    copied!<p>I've only dealt with one-to-one relationships in php so far, but I'm stuck on a problem which involves a one-to-many relationship. I've been sitting on this for a few days with no luck, so I'm desperate for someone to step in and show me a solution before I lose my mind.</p> <p>In my database have a series of urls, which are received by a SELECT query along with various other fields, from different tables. Every url has at least one category associated with it, but can have multiple categories. So in my results I might see something that looks a bit like this:</p> <pre><code>link_id = 3 url= 'http://www.somesite1.com' category = 'uncategorised' link_id = 4 url= 'http://www.somesite2.com' category = 'travel' link_id = 4 url= 'http://www.somesite2.com' category = 'fun' link_id = 4 url= 'http://www.somesite2.com' category = 'misc' link_id = 3 url= 'http://www.somesite3.com' category = 'uncategorised' </code></pre> <p>I have got this to work, kind of. When I loop through and print them off, using a while loop and mysql fetch array, the result looks exactly like it does above. Thats great, except what I need is for it to read something like:</p> <pre><code>link_id = 4 url = 'http://www.somesite2.com' category = 'travel fun misc' </code></pre> <p>So that basically all of the categories for each url get combined somehow, as they are printed out. My first attempt led me to try a nested while loop, but it didn't work and i'm not sure if this is feasible. Apart from that I'm wondering if I might need a multidimensional array (complete guess, i've never had to use one before).</p> <p>I'm ordering these results by link id as above, so I know if the link id in the current loop iteration, matches the one in the last iteration - then I have something which has more than one category.. I think I'm really close, but I just can't figure it out.</p> <p>Any ideas?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload