How do I create a loop based off this array?
I'm trying to process this array, first testing for the presence of a check, then extrapolating the data from quantity to return a valid price.
Here's the input for fixed amounts of items, with no variable quantity.
<input type="checkbox" name="measure[<?=$item->id?>][checked]" value="<?=$item->id?>">
<input type="hidden" name="measure[<?=$item->id?>][quantity]" value="1" />
Here's the inputs for variable amounts of items.
<input type="checkbox" name="measure[<?=$item->id?>][checked]" value="<?=$item->id?>">
<input class="item_mult" value="0" type="text" name="measure[<?=$item->id?>][quantity]" />
So, the resulting array is multidimensional. Here's an output:
Array (
[1] => Array ( [quantity] => 1 )
[2] => Array ( [quantity] => 1 )
[3] => Array ( [quantity] => 1 )
...
[14] => Array ( [checked] => 14 [quantity] => 999 )
)
Here's the loop I'm using to take this array and process items checked off the form in the first place. I guess the question essentially boils down to how do I structure my conditional statement to incorporate the multi-dimensional array?
foreach($field as $value):
if ($value['checked'] == TRUE) {
$query = $this->db->get_where('items', array('id' => $valu开发者_开发问答e['checked']))->row();
#Test to see if quantity input is present
if ($value['quantity'] == TRUE) {
$newprice = $value['quantity'] * $query->price;
$totals[] = $newprice;
}
#Just return the base value if not
else {
$newprice = $query->price;
$totals[] = $newprice;
}
}
else { } ?>
<p><?=$query->name?> - <?=money_format('%(#10n', $newprice)?></p>
<? endforeach; ?>
My question: How can I change my loop to work with the multidimensional array?
I've found at least 2 errors:
- put a declaration of
$newprice
outside the scope of the main if, otherwise it is not avaiable outside it, in themoney_format
call - before checking the values of arrays, check if the value is set with the
isset
function.
So the code will be
foreach($field as $value):
$newprice = 0;
if (isset($value['checked']) && $value['checked'] == TRUE) {
$query = $this->db->get_where('items', array('id' => $value['checked']))->row();
#Test to see if quantity input is present
if (isset($value['quantity']) && $value['quantity'] == TRUE) {
$newprice = $value['quantity'] * $query->price;
$totals[] = $newprice;
}
#Just return the base value if not
else {
$newprice = $query->price;
$totals[] = $newprice;
}
}
else { } ?>
<p><?=$query->name?> - <?=money_format('%(#10n', $newprice)?></p>
<? endforeach; ?>
You shouldn't be comparing against true in an if statement. Simply use the bare expression and let PHP check its "trueness":
if ($value['checked']) {
....
if ($value['quantity']) {
精彩评论