1

我不确定这是否可能,因为我对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>

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

4

1 回答 1

3

您的第一个循环基本上只是不断覆盖 $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>';
于 2012-11-18T13:06:43.877 回答