PHP array loop problem - help

Discussion in 'PHP' started by nepalsites, Sep 9, 2008.

  1. #1
    i am trying to use the foreach array loop to display the generated news. The news has "news source", "news title", "News link" and "news date". I need to display the news date and new source in one line and news title with the news link in next line.

    Here's what i have done -



    expected output
    source1 - date1
    test1

    source2 - date2
    test2

    source3 - date3
    test3



    when i use single parameter like below it works fine


    but i need the output above and when i put foreach loop inside the foreach loop doesn't give the expected results. it just gives repeated values of the variables. what am i doing wrong?


    Please help! :confused:
     
    nepalsites, Sep 9, 2008 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    
    foreach ($news_source AS $key => $value)
    {
        echo $news_source[$key], ' ', $news_date[$key], "<br />\n";
        echo "<a href=\"{$news_link[$key]}\">{$news_title[$key]}</a><br /><br />\n";
    }
    
    PHP:
     
    nico_swd, Sep 10, 2008 IP
  3. zerxer

    zerxer Peon

    Messages:
    368
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I'd clean it up a bit and use a multi-dimensional array rather than all those other arrays :<

    <?
    $news[] = array("source" => "source1",
                    "title" => "test1",
                    "link" => "http://www.test1.com",
                    "date" => "date1");
    //etc, or alternatively:
    
    $news[0]['source'] = "source1";
    $news[0]['title'] = "test1";
    $news[0]['link'] = "http://www.test1.com";
    $news[0]['date'] = "date1";
    
    //etc, slowly incrementing 0 by one as you add different news stories
    //then for your loop...
    
    foreach($news as $n) {
      ?><?=$n['source']?> - <?=$n['date']?><br />
          <a href="<?=$n['link']?>"><?=$n['title']?></a><br /><br />
      ?>
      //or if that seems a bit complex to you for whatever reason, nico_swd's echo method
      echo $n['source'], ' - ', $n['date'], "<br />\n";
      echo "<a href=\"{$n['link']}\">{$n['title']}</a><br /><br />\n";
    }
    ?> 
    PHP:
     
    zerxer, Sep 10, 2008 IP