Page 1 of 1

Need help with list() and array() code Please... I'm stuck!

Posted: Wed Nov 15, 2006 1:01 pm
by idotcom
Hi,

I'm trying to figure out a way to build an array from list() in a foreach().

I need to be able to create a key=value array from list so that I can compare the var=value from the list() to another set coming from while().

Example:


I have this code that fills existing variables from an order which is stored like this

1^200^200.00^566^|1^300^300.00^567

Code: Select all

$items = explode("|", $items);
foreach($items as $value)
{
list($item_qty, $item_price, $item_total, $item_id) = explode("^", $value);
}
Then I have this code that grabs the fixed items and values for each item in inventory

Code: Select all

while($itemrow = mysql_fetch_array($item_results))
{
$inv_item_id = $itemrow["item_id"];
$inv_item_price = $itemrow["item_price"];
?>

form input: price (value=<?$inv_item_price?>)

<?
}
What I need to be able to do is compare the two with something like this:

Code: Select all

while($itemrow = mysql_fetch_array($item_results))
{
$inv_item_id = $itemrow["item_id"];
$inv_item_price = $itemrow["item_price"];

if($item_id == $inv_item_id && $item_qty > 0)
{
$inv_item_price = $item_price;
}

?>

form input: price (value=<?$inv_item_price?>)

<?
}


What's going on above is this.... I have a form which is filled with a bunch of items from inventory with id, name, price, etc.

But when I'm updating and order, I need the existing items to replace the inventory items, otherwise, I have to re-enter qty and price when updating the order. I really hope this makes sense....

So I just need a way to make the array usable in the while(), from the list() without being in the while().

Thanks in advance for any help.

Posted: Wed Nov 15, 2006 2:10 pm
by volka
If you want an array you have to build an array.
list($item_qty, $item_price, $item_total, $item_id) = explode("^", $value);
overwrites the variables in each iteration of the loop.

try

Code: Select all

$items = '1^200^200.00^566^|1^300^300.00^567';
$tmp = explode("|", $items);
$items = array();
foreach($tmp as $e) {
	$e = explode('^', $e);
	$items[$e[3]]	= array('qty'=>$e[0], 'price'=>$e[1], 'total'=>$e[2]);
}

echo '<pre>items: '; print_r($items); echo "</pre>\n";