Reputation: 1884
I use foreach loop but it always gives an wierd result in the first but others are fine so i want to remove 1st loop and continue from 2nd...
My code is
foreach($doc->getElementsByTagName('a') as $a){
foreach($a->getElementsByTagName('img') as $img){
echo $a->getAttribute('href');
echo $img->src . '<br>';
}
}
Upvotes: 6
Views: 27304
Reputation: 11
You could also try array slice in PHP:
foreach(array_slice($doc->getElementsByTagName('a'),1) as $a){
foreach(array_slice($a->getElementsByTagName('img'),1) as $img){
echo $a->getAttribute('href');
echo $img->src . '<br>';
}
}
Upvotes: 1
Reputation: 382696
$counter = 0;
foreach($doc->getElementsByTagName('a') as $a){
foreach($a->getElementsByTagName('img') as $img){
if ($counter++ == 0) continue;
echo $a->getAttribute('href');
echo $img->src . '<br>';
}
}
Upvotes: 18
Reputation: 367
If you don't wanna define an extra counter:
foreach($doc->getElementsByTagName('a') as $a){
foreach($a->getElementsByTagName('img') as $img){
if ( $a === reset( $doc->getElementsByTagName('a') ) && $img === reset( $a->getElementsByTagName('img') ) ) continue;
echo $a->getAttribute('href');
echo $img->src . '<br>';
}
}
I don't know which will perform better.
Upvotes: 0
Reputation: 3901
The simplest way I can think of in order to skip the first loop is by using a flag
ex:
$b = false;
foreach( ...) {
if(!$b) { //edited for accuracy
$b = true;
continue;
}
}
Upvotes: 14
Reputation: 1300
try something like this
foreach($doc->getElementsByTagName('a') as $a)
{
$count = 0;
foreach($a->getElementsByTagName('img') as $img)
{
if(count == 0)
{
$count++;
continue;
}
echo $a->getAttribute('href');
echo $img->src . '<br>';
}
}
Upvotes: 3
Reputation: 15338
$nm = 0;
foreach($doc->getElementsByTagName('a') as $a){
if($nm == 1){
foreach($a->getElementsByTagName('img') as $img){
echo $a->getAttribute('href');
echo $img->src . '<br>';
}
}
$nm=1;
}
Upvotes: 1