سؤال

I'm re-writing a coldfusion page in PHP. I have an indexed cfloop and within it a cfoutput query. It looks like this:

    <h2>Choose up to Five Counties:</h2>
<cfif results.recordcount gt 0>
<cfloop from="1" to="5" step="1" index="i">
<!--- Looping Data --->
    <cfoutput>
    <select name="counties" style="width:150px; font-family:Arial,Helvetica; font-size:11px;">
        <option value="">- select county -
    </cfoutput> 
        <cfoutput query="results">
            <option value="#County_Name#" style="font-family:Arial,Helvetica; font-size:12px;">#County_Name#</option>
        </cfoutput> 
    </select>
</cfloop>
</cfif>

This code loops over the select tag code 5 times and loops over a MSSQL query option tag output. I've written the PHP side and it looks like this:

<h2>Choose up to Five Counties:</h2>

 <?php if(count($results) > 0) { 
    for ($i=0; $i<count($results); $i++) {
                 if ($i == 5) {
                    break;
                   } ?>

    <select name="counties" style="width:150px; font-family:Arial,Helvetica; font-size:11px;">
        <option value="">- select county -

            <?php for ($i=0; $i < count($results); $i++) { ?>

            <option value="<?php echo $results[$i]['County_Name']; ?>" style="font-family:Arial,Helvetica; font-size:12px;"><?php echo $results[$i]['County_Name']; ?></option>

            <?php } ?>

    </select>
     <?php } ?>
  <?php }; ?>

The inner index for loop works just fine, but I can only get the outer loop to display the select tag code once and not five times (which is what I need).

Any suggestions?

هل كانت مفيدة؟

المحلول

The issue is you're using $i in both loops. So the first time it loops through the second loop, it's resetting to 0 every time.

Change your second loop variable to something like this:

<?php for ($x=0; $x < count($results); $x++) { ?>
<option value="<?php echo $results[$x]['County_Name']; ?>" style="font-family:Arial,Helvetica; font-size:12px;"><?php echo $results[$x]['County_Name']; ?></option>
<?php } ?>

نصائح أخرى

The first loop should be for ($i=0; $i<5; $i++) instead of for ($i=0; $i<count($results); $i++), if you want it to show select five times.

Also, don't use $i for both loops, as TNC mentioned in his answer. That is why the loop exits after the first select.

Although you could translate line for line the above, the below may be slightly more efficient. Assuming you are using the mssql_* function set:

<?php
$query = myssql_query('SELECT * ....');
?>

<h2>Choose up to Five Counties:</h2>
<select name="counties" style="width:150px; font-family:Arial,Helvetica; font-size:11px;">

<?php
while($results = mssql_fetch_assoc($query)){
    echo "<option value=\"{$results['County_Name']}\" style=\"font-family:Arial,Helvetica; font-size:12px;\">{$results['County_Name']}</option>";
}
?>

</select>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top