Efekan
Efekan

Reputation: 1505

foreach in foreach only echos last item?

I am trying to extract download links from a site. However i only get the last item in my array.

<?php
    require 'functions/simple_html_dom.php';
    $html = new simple_html_dom();
    $html->load_file('http://www.nyaa.eu/?page=torrents&user=64513');
    $page_title = $html->find('title',0);
    ?>

    Title:<?php echo $page_title->plaintext; ?><br><br>
    Links:<br>
    <?php
    foreach($html->find('td.tlistdownload a') as $links){
        $dllinks[] = $links->href;
    }
    foreach($html->find('td.tlistname a') as $names){
        echo '<a href="'; 
        foreach ($dllinks as $value)
        {
            echo $value;
        }
        echo '">' . $names->innertext . '</a><br>';
    }
    foreach ($dllinks as $value)
    {
        echo $value . '<br>';
    } 
?>

When I use var_dump it shows all the download links in my array. But for some strange reason it only shows the last item in the second foreach loop.


EDIT:
Sorry it was supposed to be like this

    <?php
    require 'functions/simple_html_dom.php';
    $html = new simple_html_dom();
    $html->load_file('http://www.nyaa.eu/?page=torrents&user=64513');
    $page_title = $html->find('title',0);
    ?>

    Title:<?php echo $page_title->plaintext; ?><br><br>
    Links:<br>
    <?php
    foreach($html->find('td.tlistdownload a') as $links){
        $dllinks[] = $links->href;
    }
    foreach($html->find('td.tlistname a') as $names){
        echo '<a href="'; 
        foreach ($dllinks as $value)
        {
            echo $value;
        }
        echo '">' . $names->innertext . '</a><br>';
    }
?>

Upvotes: 0

Views: 196

Answers (1)

Stephen
Stephen

Reputation: 3432

I kept this verbose so its easier to see whats going on... Basically, grab each row.. Find the name and the link from the row. spit it out..

<?php
require 'functions/simple_html_dom.php';
$html = new simple_html_dom();
$html->load_file('http://www.nyaa.eu/?page=torrents&user=64513');
$page_title = $html->find('title',0);
?>

Title:<?php echo $page_title->plaintext; ?><br><br>
Links:<br>
<?php
foreach($html->find('.tlistrow') as $row){
    $link_nodes = $row->find('td.tlistdownload a');
    $name_nodes = $row->find('td.tlistname a');
    if (count($link_nodes) > 0 && count($name_nodes) > 0) {
      $link = $link_nodes[0]->href;
      $name = htmlentities($name_nodes[0]->innertext);
      echo "<a href='{$link}'>{$name}</a>\n";
    }
}

Upvotes: 1

Related Questions