Jump to content

Need Help Working with Array & Database Result


mclamais

Recommended Posts

The Goal is:

A Mini-Cart for displaying Quantity & Product Title.

 

I need a little help working with data I have in an array and database results.

 

From other site, I get a URL with product sku's and quantities, formatted as

 

?p=100593825_1,100593826_2,100593826_1 or ?p=[sku]_[quantity],

 

I then to use the sku's, to lookup the product titles.  My code so far is:

 

//temp values
$p = '100593825_1,100593826_2,100593826_1';

$item =  explode(",", $p);

$skus = array();
$quant = array();

foreach (explode(',',$p) as $tmp){
   list($skus[],$quant[]) = explode('_',$tmp);
}
$skulist = implode(',',$skus) ;
   
$query1  = "SELECT product_name FROM products WHERE sku IN (".$skulist.")";

 

The question is, how do I display the results of the query, with the quantity values in the array so they are properly related.  Or is there just a better way to did this?

 

I need display the results like

 

Qty    Product

1      Product Title Here

2      Another Product Title

 

Thanks for the help, as I'm really need to PHP.

<?php

$p = '100593825_1,100593826_2,100593826_1';

$items = array();

foreach (explode(",", $p) as $input) {
list($sku, $quantity) = explode("_", trim($input));
// You'll get a php notice for each undefined element in the array
// this way, but they don't mean anything
$items[$sku] += $quantity;

/*
// alternatively, without the php notices:
if ($items[$sku]) {
	$items[$sku] += $quantity;
} else {
	$items[$sku] = $quantity;
}
*/
}

$query = "SELECT sku, product_name FROM inventory WHERE sky IN(" . implode(",", array_keys($items)) . ")";

$result = mysql_query($query);

while ($row = mysql_fetch_assoc($result)) {
echo $items[$row['sku']] . " " . $row['product_name'] . " were requested.<br />";
}

Wow, thanks a lot.

 

I find the quantities are not correct, the sample data is

 

$p = '100593825_1,100593826_2,100593826_1';

where quantities are 1,2,1 respectively

 

but my results are

 

1 [product name] were requested.

3 [product name] were requested.

1 [product name] were requested.

 

Also, I tried the alternate code

 

	// alternatively, without the php notices:
if ($items[$sku]) {
	$items[$sku] += $quantity;
} else {
	$items[$sku] = $quantity;
}

 

and it does show the errors

 

Notice: Undefined index: 100593825

Notice: Undefined index: 100593826

 

Any way to avoid this?

 

Thanks again.

 

 

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.