I came up with the following code:
<?php
if (block_rows('option') : while ( block_rows( 'option' ) ) : block_row( 'option' );
if ( !isset($id) ) { // meet only on the first iteration
$a = 1;
}
elseif ( isset($id) && $id == block_sub_value('ID') ) {
$a ;
}
elseif ( isset($id) && $id != block_sub_value('ID') ) {
$a = 2;
}
$id = block_sub_value('ID');
?>
<h1> Option - <?=$id;?> </h1> // prints only the ID
<p> Sub Option - <?=$id . ' - ' . $a;?> <p> prints ID and the $a
<?php endwhile; endif;?>
The logic I'm trying to build is:
- If is the first iteration of the loop, $a must be equal to 1. Period.
- If $id and $a are equal, increase $a value by 1.
- And finally, if $id and $a are different, $a must be equal to 2.
I have a list with some parent titles that has a $id number and child contents that has the parent $id number and also the $a number. Something like:
The point that don't seen to work well is actualy is the first condition. The very first $a starts with 2, not 1, almost like if after meeting the firts condition, the function continues to test the others, replacing the $a value.. I don't know why this happening.
CodePudding user response:
Once you started the while loop and passed the 1st iteration, isset($id) is true and so will not be reset to 1
Hence change the part:
<?php
if (block_rows('option') : while ( block_rows( 'option' ) ) : block_row( 'option' );
if ( !isset($id) ) { // meet only on the first iteration
$a = 1;
}
// the rest of the code
to something like:
<?php
// set initial $oldid to be a value which is not possible
$oldid="-100";
if (block_rows('option') : while ( block_rows( 'option' ) ) : block_row( 'option' );
if ( $oldid !=$id ) { // meet only on the first iteration
$oldid=$id;
$a = 1;
}
// the rest of the code (please further amend if logically requires)
This is just one of the ways. Hope that it gives you some ideas