【问题标题】:Using foreach in a while statement在 while 语句中使用 foreach
【发布时间】:2012-11-06 13:54:00
【问题描述】:

我不确定这是否可行,因为我对foreach 语句没有太多经验,但这就是我所拥有的

<?php $string = file_get_contents('data.xml') ?>

<?php

include("../connect.php");

$xml = new SimpleXMLElement($string);

//Loop trough multiple products
print "<table border='1' bordercolor='#6600FF' style='width='100%' cellpadding='3' cellspacing='3'>
<th>Campaign Name</th><th>Countries</th><th>Rate</th><th>Cash</th><th>Points</th>";

$cats = mysql_query("SELECT * FROM `offer_cats`");

while ($off = mysql_fetch_array($cats)) {

    $cnames = array($off['name']);
    $cnamess = implode(",", $cnames);
    $cname = explode(",", $cnamess);

    print_r($cnames);

    foreach ($cnames as $category) {
        $cat = $category;
    }

}

foreach($xml->item as $item) { 

    $count = count(explode(", ",$item->countries));

    if ($count >= 5) {
        $country = "ALL INTL";
    } else {
        $country = $item->countries;
    }

    $rate = number_format((float)$item->rate, 2, '.', '');
    $crates = $rate * 0;
    $prates = $rate * 45;
    $crate = number_format((float)$crates, 2, '.', '');
    $prate = number_format((float)$prates, 2, '.', '');

    echo'<tr><td>'.$item->name.'<br /><font color="limegreen" size="2">Incent: '.$item->incent.'</font><br /><select name="req" style="width:200px"><option value ="'.$item->requirements.'">'.$item->requirements.'</option></select>
<select style="width:200px" name="cat" id="cat"><option value="'.$cat.'">'.$cat.'</option></select><input type="button" name="add" value="+" /></td>';    
    echo '<td>'.$country.'</td>';
    echo '<td>'.$item->rate.'</td>';
    echo '<td><input type = "text" name="cash" value="'.$crate.'" style = "width:75px" /></td>';
    echo '<td><input type = "text" name="points" value="'.$prate.'" style = "width:75px" /></td>';
    // echo $item->incent;
    // echo '<br/>';
}
?>

</tr>
</table>

我正在尝试加载这一行 &lt;select style="width:200px" name="cat" id="cat"&gt;&lt;option value="'.$cat.'"&gt;'.$cat.'&lt;/option&gt;&lt;/select&gt; 中的所有类别,但它始终只加载数组中的最后一个类别。虽然我很确定 implodeexplodes 并不是真正需要的,但它试图修复错误,但它是徒劳的。我到底做错了什么?

【问题讨论】:

    标签: php arrays foreach while-loop


    【解决方案1】:

    您的第一个循环基本上只是不断覆盖 $cat 变量:

    foreach($cnames as $category){
        $cat = $category;
    }
    

    你需要把这个循环放到你想要循环的地方并输出选项,比如

    echo '<select style="width:200px" name="cat" id="cat">';
    foreach($cnames as $category){
        echo '<option value="'.$cat.'">'.$cat.'</option>';
    }
    echo '</select>';
    

    【讨论】:

    • 当我用它移动while语句时它只显示完整列表,即使这样它也只显示代码中第二个foreach的第一行数据的完整列表:/
    猜你喜欢
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    • 2017-05-02
    • 2015-07-06
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    相关资源
    最近更新 更多