kira423
kira423

Reputation: 427

Using foreach in a while statement

I am not sure if this is possible since I do not have much experience with foreach statements, but this is what I have

<?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>

I am trying to load all of the categories in this line <select style="width:200px" name="cat" id="cat"><option value="'.$cat.'">'.$cat.'</option></select> but it always loads only the last category in the array. Although I am pretty sure that the implode and explodes aren't really needed, it was an attempt to fix the error, but it was in vain. What exactly am I doing wrong?

Upvotes: 1

Views: 150

Answers (1)

duellsy
duellsy

Reputation: 8577

Your first loop essentially just keeps overwriting the $cat variable:

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

You need to put this loop instead down where you want to loop through and output the options, like

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

Upvotes: 3

Related Questions