开发者

Two foreach loops in PHP

开发者 https://www.devze.com 2023-02-01 02:53 出处:网络
My code is a simple links script. I need two foreach loops, one which loops my sites and 开发者_开发知识库one which loops my anchors. So I\'ll have

My code is a simple links script. I need two foreach loops, one which loops my sites and 开发者_开发知识库one which loops my anchors. So I'll have

<li>link to site1 and anchor to site1</li>
<li>link to site2 and anchor to site2</li>
<li>link to site3 and anchor to site3</li>

$currentsite = ''.bloginfo('wpurl').'';
$mysites = array('http://site1.com', 'http://site2.com', 'http://site3.com');
$myanchors = array('anchor1','anchor2','anchor3');
foreach($mysites as $mysite) ****** I need a foreach loop for the anchors array *******
{
    if ( $mysite !== $currentsite ){
        echo '<li><a href="'.$mysite.'" title="'.$myanchor.'">'.$myanchor.'</a></li>';
    }
}

How to?


I'm guessing you're trying to write out the links with the anchors.. Just use one array like this:

$mysites = array(
    'anchor1' => 'mysite.com',
    'anchor2' => 'mysite2.com'
);

foreach($mysites as $anchor => $site) {
    if($site === $currentsite) { continue; }
    echo '<li><a href="'.$site.'" title="'.$anchor.'">'.$anchor.'</a></li>';
}


// Assuming that $mysites and
// $myanchors have same sizes.
for ( $i = 0; $i < length($mysites); ++$i )
{
  $mysite = $mysites[ $i ];
  $myanchor = $myanchors[ $i ];
  // ...
}


I would recommend to use an associative array with anchors as keys for the sites.

Then you could loop through this array and echo the values. In your example, $myanchor is never set.

$mysites = array(
        'anchor1' => 'http://site1.com', 
        'anchor2' => 'http://site2.com', 
        'anchor3' => 'http://site3.com');

    foreach ($mysites as $anchor => $site) { //****** i need a foreach loop for the anchors array *******
        if ($site !== $currentsite) {
            echo '<li><a href="' . $site . '" title="' . $anchor . '">' . $anchor . '</a></li>';
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消