PHP函数嵌套的foreach循环不起作用

时间:2013-12-20 10:51:05

标签: php

当我通过函数调用它时,为什么这段代码不起作用?它只适用于外部循环,但内部循环不返回值?

<?php populateEnrollment($products); ?>

<?php
function populateEnrollment($value){

    foreach($value as $productid => $prod) if ($productid ==101)
    { 
        echo '<tr>';
        echo '<td width=300 class="tah11">'. $prod["name"] .'</td>' ;
        echo '<td width=100 class="tah11"><div align="center"> <select name="enrollName"id="enrollNameId" >';
            foreach ($prod["membershipType"] as $type)
            {
                echo '<option value="' .$type["price"]; $typeIdPrice = $typeId["price"] .'">'.$type["name"] . ' at $' . $typeIdPrice . '</option>';
                echo '</select>';
                echo '</td>';                               
            } // end of foreach membershipTypen
    } // end of products foreach
} // end of function populateEnrollment
?>

2 个答案:

答案 0 :(得分:2)

请在内部foreach循环旁边添加echo </select></td>

您回复<option>的方式也是错误的,请点击此处

将$ typeId更改为$ type .. minor typo update

<?php
function populateEnrollment($value){

    foreach($value as $productid => $prod) if ($productid ==101){ 
    echo '<tr>';
    echo '<td width=300 class="tah11">'. $prod["name"] .'</td>' ;
    echo '<td width=100 class="tah11"><div align="center"> <select name="enrollName"id="enrollNameId" >';
    foreach ($prod["membershipType"] as $type){
           echo '<option value="' .$type["price"] .'">'.$type["name"] . ' at $' . $type["price"] . '</option>';

    } // end of foreach membershipTypen

    echo '</select>';
    echo '</td>';                               

    } // end of products foreach
} // end of function populateEnrollment
?>

答案 1 :(得分:0)

你可以这样做

<?php populateEnrollment($products); ?>

function populateEnrollment($value)
{

    foreach($value as $productid => $prod) 
    { 
        if ($productid ==101)
        {
            ?><tr><?php
            ?><td width=300 class="tah11"><?=$prod["name"]?></td><?php
            ?><td width=100 class="tah11"><div align="center">
                <select name="enrollName"id="enrollNameId" >
                <?php
                foreach ($prod["membershipType"] as $type)
                {
                    echo '<option value="' .$type["price"]; $typeIdPrice = $typeId["price"] .'">'.$type["name"] . ' at $' . $typeIdPrice . '</option>';
                }
            ?></td><?php
            ?></tr><?php
        }
    }
}