Loop in loop

Discussion in 'PHP' started by Derpost, May 28, 2012.

  1. #1
    Hi Mate!
    I want to create simple poll system. I have two question and two answers. First Question has two answer but second question hasn't any answer. In a sense I want to get:
    
    First question?
    Answer1
    Answer2
    
    Second question?
    
    Code (markup):

    But I'm getting
    First question?
    Answer1
    Answer2
    
    Second question?
    Answer1 
    Answer2
    
    Code (markup):
    Second question need not to have Answer1 and Answer2(same with First question answers but I have two answer in mysql).

    And my foreach loops.. How need i to change my loops?
    
    foreach($sorular->soruCek($_GET["kategori"]) as $data) // Questions
    {
        echo $data["soru"] . "<br/>";
        foreach($sorular->cevapCek($data["id"]) as $cevaplar) // Answers
        {
            echo $cevaplar["cevap"] . "<br/>"; // This needn't print data to below of Second Question
        }
    }
    
    PHP:
    @Yusuf Ali Bozkir
     
    Derpost, May 28, 2012 IP
  2. ROOFIS

    ROOFIS Well-Known Member

    Messages:
    1,234
    Likes Received:
    30
    Best Answers:
    5
    Trophy Points:
    120
    #2
    does it need to be echoed in the first place?
     
    ROOFIS, May 28, 2012 IP
  3. Derpost

    Derpost Active Member

    Messages:
    95
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    61
    #3
    yes. shortly $cevaplar["cevap"] is Answer1 Answer2 but for only first question..
     
    Derpost, May 28, 2012 IP
  4. HostPlanz

    HostPlanz Well-Known Member

    Messages:
    449
    Likes Received:
    34
    Best Answers:
    4
    Trophy Points:
    130
    #4
    The following may work for only 2 questions but isn't a flexible way of doing what you want for multiple questions.
    I don't know what you're trying to achieve.

    foreach($sorular->soruCek($_GET["kategori"]) as $data) // Questions
    {
        echo $data["soru"] . "<br/>";
        foreach($sorular->cevapCek($data["id"]) as $cevaplar) // Answers
        {
          if ($data["soru"] == "First Question")//Change "First Question" to what your first question string is
          {
           echo $cevaplar["cevap"] . "<br/>"; // This needn't print data to below of Second Question
          }
        }
    }
    PHP:
     
    HostPlanz, May 28, 2012 IP
  5. Derpost

    Derpost Active Member

    Messages:
    95
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    61
    #5
    These Codes are only example for you understand. I'm using mysql database with these codes and I have more than 100 questions and answers.
     
    Derpost, May 29, 2012 IP