Hi Guys,
I'm from a VB; Access; SQL Server background recently introduced to WAMP.
I have two arrays filled from MySQL recordsets, one for the site Cart and the other for one of the site departments (catalogs) see a manual interpretation below. -
$catalog[] = array(
-
array('ProdID'=>2,'Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
array('ProdID'=>6,'Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
array('ProdID'=>7,'Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
array('ProdID'=>8,'Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
array('ProdID'=>9,'Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
);
-
-
-
$cart[] = array(
-
array('Name'=>'Alpha2','Loc'=>'e_vol1','BasketID'=>'81','ProdID'=>'2','Quant'=>'1'),
-
array('Name'=>'Beta4','Loc'=>'e_vol2','BasketID'=>'81','ProdID'=>'4','Quant'=>'1'),
-
array('Name'=>'Alpha8','Loc'=>'e_vol3','BasketID'=>'81','ProdID'=>'8','Quant'=>'1'),
-
array('Name'=>'Gamma21','Loc'=>'e_vol4','BasketID'=>'81','ProdID'=>'21','Quant'=>'1'),
-
);
-
What I need to do is loop through the catalog array each time a new catalog is chosen, comparing the ProdID of the cart against the catalog, when a match is found I would like to update the 'InBasket' value to '1' this will indicate the item is already in the customers cart which I can then show on screen (The customer is only allowed to purchase one of each item).
I have tried some loops but they don't seem to work. -
for ($x = 0; $x < count($catalog); $x++)
-
{
-
for ($y = 0; $y < count($cart); $y++)
-
{
-
If ($catalog[$x]['ProductID'] == $cart[$y]['ProductID'] )
-
{
-
$cart[$x]['InBasket'] = 1;
-
}
-
}
-
}
-
Any ideas would be appreciated.
21 3243
Three quick comments about your looping code
1. check the php manual, you will see that the structure you created is not the most efficient. A better option is to calculate the size of the array only once and test against the size variable like this:
for($i = 0, $size = count($catalog); $i < $size; ++$i)
2. In your code no matter how many products are found the answer will always be 1, because you are just setting the value of inBasket to 1
$cart[$x]['InBasket'] = 1;
what I suspect you want to do is increment the value by one.
$cart[$x]['InBasket'] += 1; or $cart[$x]['InBasket'] ++;
3. You may want to use an associative array instead of a numerical array for quicker look-up. That way you do not have to loop through the array.
Look at example #7 in the online php manual
Hi Claus
Thanks for your reply. We both may be a little confused here, my idea (as in VB6) was to loop through each catalog row (record) comparing it with each row in the Cart array, if the 'fields' match on the ProductID then I can update the catalog 'field' InBasket for that row. I only ever want InBasket to be 0 or 1 (true/ false) so that when the web page is constructed I can inform the user about these products to stop them selecting a duplicate product, this action will happen every time a new catalog is chosen.
The probability is there will never be more than 10 items in a catalog and 3 - 5 in the cart.
I could not see how example #7 would update a 'field' perhaps you could explain ?
I thought I already had an associative array, is there a different looping method ?
Kind regards
hmm, you want to minus the quantity of the item when it is in the cart of other customer am i correct? if that so, you need to have the code in the on load and offload. but i think it's difficult,
Not sure where you are keeping track of selected items. On the user's browser? In a session on the web server? Are you doing ajax lookup calls each time the user selects an item to update the cart? or is the user submitting a form for each item?
My thought was to restructure the catalog array. The way you wrote the arrays, both the catalog and cart arrays are numerical arrays. The sub-arrays within each cell is an associative array.
As your arrays sit the way you wrote them, you access each cell with $catalog[1] etc. Check out the revised code below. And in thinking about it you really could also eliminate that other loop. Just pass the product ids selected and stream out the results. - <?php
-
//What if you use this part of example 7
-
$array = array(
-
"multi" => array(
-
"dimensional" => array(
-
"array" => "foo"
-
)
-
)
-
);
-
-
//and wrote the catalog array like this
-
$catalog = array(
-
'PID2' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
'PID6' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
'PID7' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
'PID8' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
'PID9' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0')
-
);
-
-
//modify the cart array like this
-
$cart[] = array(
-
array('Name'=>'Alpha2','Loc'=>'e_vol1','BasketID'=>'81' ,'ProdID'=>'PID2','Quant'=>'1'),
-
array('Name'=>'Beta4','Loc'=>'e_vol2','BasketID'=>'81' ,'ProdID'=>'PID4','Quant'=>'1'),
-
array('Name'=>'Alpha8','Loc'=>'e_vol3','BasketID'=>'81' ,'ProdID'=>'PID8','Quant'=>'1'),
-
array('Name'=>'Gamma21','Loc'=>'e_vol4','BasketID'=>'81','ProdID'=>'PID21','Quant'=>'1'),
-
);
-
-
//update the catalog array like this as shown in example 7 "var_dump($array["multi"]["dimensional"]["array"]);"
-
for ($i = 0, $size = count($cart); $i < $size; ++$i)
-
{
-
$thisProduct = $cart[$i]['ProductID'];
-
$catalog[$thisProduct]['InBasket'] = 1;
-
}
-
}
-
?>
@lyodmichael
Hi lyodmichael
Not sure you are answering the same question I submitted.
BY THIS
The probability is there will never be more than 10 items in a catalog and 3 - 5 in the cart
I MEAN THIS
The probability is there will never be more than 10 items in a catalog and BETWEEN THREE AND FIVE in the cart
Kind Regards
Hi Claus
This is the code I use to extract data from MySQL via stored Procs. The web site data is either kept in SESSION variables but always in the database and retrieved when required.
I was under the impression I already had associative arrays (correct me if I'm wrong) maybe its just the way I'm accessing the data. I do not wish to rewrite bundles of code, when what I have already my well be good enough. I have the complete web site written in ASP/VBscript//VB6 activex DLL/MS SQLserver, i'ts just that PHP/MySQL does seem to be overly complicated.
So here............. -
//Connect and get data from MySQL......
-
-
if (mysqli_num_rows($result) > 0)
-
{
-
while ($row = mysqli_fetch_array($result))
-
$cItems[] = array(
-
'Name' => $row['Name'],
-
'ProductID' => $row['ProductID'],
-
'Quantity' => $row['Quantity'],
-
'Price' => $row['Price'],
-
'LinePrice' => $row['LinePrice'],
-
'Location' => $row['Location'],
-
'Discount' => $row['Discount'],
-
'BasketID' => $row['BasketID'],
-
'countrytax' => $row['countrytax'],
-
'LineTax' => $row['LineTax']);
-
-
$_SESSION['CartItems'] = $cItems;
-
-
return true;
-
}
-
Else{
-
return false;
-
}
-
-
-
//Connect and get data from MySQL......
-
-
-
if (mysqli_num_rows($result) > 0)
-
{
-
while ($row = mysqli_fetch_array($result))
-
$tempcat[] = array(
-
'ProductID' => $row['ProductID'],
-
'Name' => $row['Name'],
-
'DepartmentID' => $row['DepartmentID'],
-
'Price' => $row['Price'],
-
'Location' => $row['Location'],
-
'DepartmentName' => $row['DepartmentName'],
-
'Discount' => $row['Discount'],
-
'InBasket' => $row['InBasket']);
-
Return $tempcat;
-
}
-
If I can't run a loop within a loop to update a field then I will look at another method, perhaps cursors on MySQL, but, I shall stay with this method for the time being.
Kind regards
Ok then here are two approaches (yours and mine)
1) Your original thought of the double loop should work, but in your example you referenced the wrong array. You said:
" What I need to do is loop through the catalog array each time a new catalog is chosen, comparing the ProdID of the cart against the catalog, when a match is found I would like to update the 'InBasket' value to '1' this will indicate the item is already in the customers cart which I can then show on screen (The customer is only allowed to purchase one of each item). ". Which I see was found in your $catalog array. But in your sample code, you are trying to update 'InBasket' in the $cart array, and that does not seem to exist. So if you fix just that one part of the code it should work. -
for ($x = 0, $size = count($catalog); $x < $size; $x++)
-
{
-
for ($y = 0, $size = count($cart); $y < $size; $y++)
-
{
-
if ($catalog[$x]['ProductID'] == $cart[$y]['ProductID'] )
-
{
-
//$cart[$x]['InBasket'] = 1;
-
$catalog[$x]['InBasket'] = 1;
-
}
-
}
-
}
-
2) The other option, which you don't want to use; would be to re-write that small piece of code to make the catalog an associative array. You said " was under the impression I already had associative arrays (correct me if I'm wrong) maybe its just the way I'm accessing the data. ". In your "while" loop your using the "push" method to create the arrays " $cItems[ ] = array(...", the use of the square bracket makes it a numeric/indexed array and not an associative array. But in fact you have a multi-dimensional array. Your first dimension is indexed and your 2nd dimension is associative. Making both dimensions associative would eliminate one loop. I understand your are hesitant to change this part of your code. But this is how I would write it: -
//Connect and get data from MySQL......
-
-
if (mysqli_num_rows($result) > 0)
-
{
-
// create an empty array
-
$cItems = array();
-
-
while ( $row = mysqli_fetch_array($result) )
- {
-
//to make both dimensions of array assoc. I add "PI" to id because I assume product id is a number.
-
$cItems[ 'PI'.$row['ProductID'] ] = array(
-
'Name' => $row['Name'],
-
'Quantity' => $row['Quantity'],
-
'Price' => $row['Price'],
-
'LinePrice' => $row['LinePrice'],
-
'Location' => $row['Location'],
-
'Discount' => $row['Discount'],
-
'BasketID' => $row['BasketID'],
-
'countrytax' => $row['countrytax'],
-
'LineTax' => $row['LineTax']
-
)
-
}
-
-
$_SESSION['CartItems'] = $cItems;
-
-
return true;
-
}else{
-
return false;
-
}
-
-
-
//Connect and get data from MySQL......
-
-
-
if (mysqli_num_rows($result) > 0)
-
{
-
while ($row = mysqli_fetch_array($result))
-
{
- //in creating the tempcat I just add the "PI" to the product id.
-
$tempcat[] = array(
-
'ProductID' => 'PI'.$row['ProductID'],
-
'Name' => $row['Name'],
-
'DepartmentID' => $row['DepartmentID'],
-
'Price' => $row['Price'],
-
'Location' => $row['Location'],
-
'DepartmentName' => $row['DepartmentName'],
-
'Discount' => $row['Discount'],
-
'InBasket' => $row['InBasket'])
-
}
-
Return $tempcat;
-
}
-
-
/*
- Now you can use the more efficient method of updating your catalog
- */
-
for ($i = 0, $size = count($tempcat); $i < $size; ++$i)
-
{
-
$thisProduct = $tempcat[$i]['ProductID'];
-
$_SESSION['CartItems'][$thisProduct]['InBasket'] = 1;
-
}
-
Take it for what it is worth. There should be no issue doing the way you originally had it laid out with the double loop.
Post and update on your success or failure.
Not sure you are answering the same question I submitted.
You are right I did throw in an additional question. I have not written a shopping cart program. It was just that I had additional ideas on how to update your session cart items. An alternate method would be to do an ajax/JSON call each time the user selected an item, in which case no loop would be required at all. And it would make your site more secure against hacking. But as you said you already have the site working in other languages. So I take that to mean that your are just trying to do a literal conversion and that is fine also. If the code works it works and that is all there is to it.
Sorry I thought you were responding to my answer. In re-reading I see you are not.
Hi Claus
I've been kept busy for the last couple of days, however, I shall try all of this over the weekend and report back.
What does the 'PI'. do?
Can I still loop through each record ?
Kind regards
I was not really sure if the PI was needed. I made the assumption that your product id was numeric, if so making the array in javaScript on the browser would be a problem (I don't think it would be a problem in php). Therefore by concatenating the "PI" with the number 9999, I could be sure it would be a string. You could try it either way.
Creating a true Assoc. Array you have to use a different for/next loop, called foreach. Instead of using 1,2,3... as array cell reference you must retrieve each key "pi1", "pi2", "pi3"... I don't use Visual Basic 6, but MS calls associative arrays Dictionaries. If you have used dictionaries in VB6 as shown here, then you should be familiar with how to loop through an associative array in php.
In php you have two options with the foreach loop.
1) you can loop through the array and get the value of each item with foreach (array_expression as $value)
or
2) you can loop through the array and get the key ie "PI2" foreach (array_expression as $key => $value). In this version the array key is assigned to $key as in this example -
foreach ($fieldList as $key => $colName )
-
{
-
$val = $tData[$key];
-
}
-
Here is how I use that to append or update any table by reading the table schema and matching it with the incoming data items stored in an assoc array. -
<?php
-
/*
-
----------------------------------------------------------------------------------------
-
uploadData adds/inserts or edits/updates data from the submitted from html page or ajax
-
request.
-
-
5 parameters are submitted:
-
1) table to be updated = $tTable
-
2) the table key/column = $tKey
-
3) the record key = $tKeyVal
-
4) data set (an assoc array) = $tData
-
5) insert (true) or update (false) = $append
-
-
usage:
-
$db->uploadData( "<table>", "<table key>", <key value>, <sanitized data>, true/false );
-
-
data is submitted in an assoc array. Each array element must have the same name as the
-
field/column name and is case sensitive ie: id and id or ID and ID, but not id and ID
-
-
data should be formatted and sanitized before calling this method to prevent sql injection
-
----------------------------------------------------------------------------------------
-
*/
-
function uploadData( $tTable, $tKey, $tKeyVal, $tData , $append )
-
{
-
/*
-
----------------------------------------
-
identify the list of fields/columns
-
in the table by calling getFieldList()
-
method which is part of this class dbcnx
-
----------------------------------------
-
*/
-
$fieldList = self::getFieldList($tTable);
-
-
/*
-
---------------------------------------
-
assemble update/insert string
-
---------------------------------------
-
*/
-
$setString = "";
-
-
/*
-
------------------------------
-
loop through table fields and
-
match with submitted data
-
------------------------------
-
*/
-
foreach ($fieldList as $key => $colName )
-
{
-
/*
-
---------------------------------------
-
if table field/column name found in
-
data get results and add to $setString
-
---------------------------------------
-
*/
-
if ( array_key_exists ( $key, $tData ) )
-
{
-
/*
-
---------------------------------------
-
get current col name
-
---------------------------------------
-
*/
-
$col = $fieldList[$key];
-
-
/*
-
---------------------------------------
-
get corrosponding data value, if any
-
---------------------------------------
-
*/
-
$val = $tData[$key];
-
-
if ($col['isAutoInc'] == "auto_increment" or
-
$col['type'] == 'binary' or
-
$col['type'] == "timestamp")
-
{
-
/*
-
---------------------------------------
-
do nothing!! Autoincrement is automatic
-
and the others not supported in HTML
-
---------------------------------------
-
*/
-
}elseif($col['type'] == "numeric" or
-
$col['type'] == "decimal" or
-
$col['type'] == "tinyint" or
-
$col['type'] == "int" or
-
$col['type'] == "mediumint" or
-
$col['type'] == "smallint" or
-
$col['type'] == "double" or
-
$col['type'] == "float")
-
{
-
if ( empty($val) )
-
{
-
$val = $col['default'];
-
}elseif ( is_numeric($val) )
-
{
-
$val = $val;
-
}else{
-
$val = number_format($val, $col['decimal'], '.', '');
-
}
-
$setString .= ( ( !empty($setString) ) ? ", " : "" ). $col['name']."=". $val;
-
}elseif ( $col['type'] == "date" )
-
{
-
$setString .= ( ( !empty( $setString ) ) ? ", ": "" ).
-
$col['name']."='".(( empty($val) ) ? $col['default'] : $val)."'";
-
-
}else
-
{
-
/*
-
---------------------------------------
-
text/char column
-
---------------------------------------
-
*/
-
$setString .= ( ( !empty($setString) ) ? ", " : "" ).
-
$col['name']."='".(( empty($val) ) ? $col['default'] : str_replace("'", "\'", $val))."'";
-
-
}// end defining column type
-
} //end if column found
-
} // end looping through table columns
-
-
/*create sql*/
-
if ( $append )
-
{
-
$sql = 'insert into '.$tTable.' set '.$setString;
-
}else{
-
$sql = 'update '.$tTable.' set '.$setString.' where '.$tKey.' = "'.$tKeyVal.'"';
-
}
-
-
/* run query*/
-
if ( $this->query($sql) )
-
{
-
$result = $this->affected_rows." record".( ( $append ) ? " was added!": "s were updated!" );
-
}else{
-
$result = "No data was ".( ( $append) ? "added!": "updated!");
-
}
-
-
/*
-
---------------------------------------
-
return the number of records affected.
-
---------------------------------------
-
*/
-
return $result;
-
-
} //end uploadData function
-
-
?>
-
Here is another example where I use both the key and the value, to load an array for back filling an HTML page. -
function loadFormWithData($dataModule, $thisTable, $key, $keyVal){
-
/*add my utility data conversion program*/
-
include("formatData.php");
-
-
/*load table specific dataModule*/
-
include($dataModule.".php");
-
-
$q = new qSetup();
-
$qSelect = $q->getSelect();
-
$qFrom = $q->getFrom();
-
$sql = "select ".$qSelect." from ".$qFrom ." where ".$key." = '".$keyVal."'";
-
-
if ( $result = $this->query($sql) ){
-
if ($result->num_rows > 0){
-
while ($row = $result->fetch_assoc()) {
-
foreach ( $row as $key => $value )
-
{
-
$value = (empty($value)) ? " ":$value ;
-
/*
-
--------------------------------------------------------
-
if reference found in $fArray (formatData.php),
-
then call associated function. pass 2 for display format
-
--------------------------------------------------------
-
*/
-
if (array_key_exists($key,$fArray))
-
{
-
$row[$key] = call_user_func($fArray[$key], $value, 2);
-
}
-
}
-
$row = $q->addCalcFields($row);
-
$aResults[] = $row;
-
}
-
}else{
-
$aResults["noRec"] = true;
-
}
-
}
-
$result->free();
-
return $aResults;
-
}//end download data to form
-
-
Hi Claus
I have found a few mistakes in my code down to human error, however, all is now well and I now give a full report below. - $catalog = array(
-
array('ProdID'=>2,'Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
array('ProdID'=>6,'Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
array('ProdID'=>7,'Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
array('ProdID'=>8,'Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
array('ProdID'=>9,'Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
);
-
-
$cart = array(
-
array('Name'=>'Alpha2','Loc'=>'e_vol1','BasketID'=>'81','ProdID'=>'2','Quant'=>'1'),
-
array('Name'=>'Beta4','Loc'=>'e_vol2','BasketID'=>'81','ProdID'=>'6','Quant'=>'1'),
-
array('Name'=>'Alpha8','Loc'=>'e_vol3','BasketID'=>'81','ProdID'=>'8','Quant'=>'1'),
-
array('Name'=>'Gamma21','Loc'=>'e_vol4','BasketID'=>'81','ProdID'=>'21','Quant'=>'1'),
-
);
I am still using a 'for loop' to update the catalog as below. - for ($y = 0, $size = count($cart); $y < $size; $y++)
-
{
-
for ($x = 0, $size = count($catalog); $x < $size; $x++)
-
{
-
if ($catalog[$x]['ProdID'] == ($cart[$y]['ProdID']))
-
{
-
$catalog[$x]['InBasket'] = 1;
-
}
-
}
-
}
When this is run the result is as shown below and you will notice the 'InBasket' cells have the correct value in them. - Array (
-
[0] => Array ( [ProdID] => 2 [Name] => Alpha [DepID] => 2 [InBasket] => 1 )
-
[1] => Array ( [ProdID] => 6 [Name] => Alpha [DepID] => 2 [InBasket] => 1 )
-
[2] => Array ( [ProdID] => 7 [Name] => Alpha [DepID] => 2 [InBasket] => 0 )
-
[3] => Array ( [ProdID] => 8 [Name] => Alpha [DepID] => 2 [InBasket] => 1 )
-
[4] => Array ( [ProdID] => 9 [Name] => Alpha [DepID] => 2 [InBasket] => 0 )
-
)
Perhaps you could show me the foreach version for this code.
Kind regards.
I was away on vacation for a few days and did not have a chance to check in. Here are the code suggestions.
While there are times that you need to loop through an associative array, the beauty of these arrays is the direct access, thereby eliminating the need for a loop. So below I show you the two ways to update your catalog with and without the "foreach" loop.
In my opinion the most efficient method for your sample code is to not loop through the catalog. But it is good to know how to use both methods. -
/*
-
----------------------------------------------------
-
In the catalog array the product id becomes the key
-
instead of the index key. I showed you in an
-
earlier post how to create this array dynamically.
-
-
The key can be created both with or without the
-
quotes. However the same method should be used
-
in both the catalog and cart arrays.
-
ie:
-
$catalog = array(
-
'2' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
);
-
-
$cart[] = array(
-
array('Name'=>'Alpha2','Loc'=>'e_vol1','BasketID'=>'81' ,'ProdID'=>'2','Quant'=>'1'),
-
);
-
-
OR:
-
$catalog = array(
-
2 => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
);
-
-
$cart[] = array(
-
array('Name'=>'Alpha2','Loc'=>'e_vol1','BasketID'=>'81' ,'ProdID'=>2,'Quant'=>'1'),
-
);
-
-
-
----------------------------------------------------
-
*/
-
$catalog = array(
-
'2' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
'6' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
'7' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
'8' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
'9' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0')
-
);
-
-
$cart[] = array(
-
array('Name'=>'Alpha2','Loc'=>'e_vol1','BasketID'=>'81' ,'ProdID'=>'2','Quant'=>'1'),
-
array('Name'=>'Beta4','Loc'=>'e_vol2','BasketID'=>'81' ,'ProdID'=>'4','Quant'=>'1'),
-
array('Name'=>'Alpha8','Loc'=>'e_vol3','BasketID'=>'81' ,'ProdID'=>'8','Quant'=>'1'),
-
array('Name'=>'Gamma21','Loc'=>'e_vol4','BasketID'=>'81','ProdID'=>'21','Quant'=>'1'),
-
);
-
-
/*
-
------------------------------------------
-
Example using "foreach" loop
-
------------------------------------------
-
*/
-
for ($y = 0, $size = count($cart); $y < $size; $y++)
-
{
-
foreach ($catalog as $key => $value )
-
{
-
if ($key == ($cart[$y]['ProdID']))
-
{
-
$catalog[$key]['InBasket'] = 1;
-
}
-
}
-
}
-
-
/*
-
------------------------------------------
-
Example eliminating the "foreach" loop
-
------------------------------------------
-
*/
-
for ($i = 0, $size = count($cart); $i < $size; ++$i)
-
{
-
$key = $cart[$i]['ProductID'];
-
$catalog[$key]['InBasket'] = 1;
-
}
-
-
Hi Claus
Hope you had a good break and are now back in full harness ?
While you were away I have been digging into the font of knowledge and have come up with the following code in a foreach loop which gives me the correct answer - $catalog = array(
-
array('ProductID'=>2,'Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
array('ProductID'=>6,'Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
array('ProductID'=>7,'Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
array('ProductID'=>8,'Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
array('ProductID'=>9,'Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
);
-
-
$cartitems = array(
-
array('Name'=>'Alpha2','Loc'=>'e_vol1','BasketID'=>'81','ProductID'=>'2','Quant'=>'1'),
-
array('Name'=>'Beta4','Loc'=>'e_vol2','BasketID'=>'81','ProductID'=>'6','Quant'=>'1'),
-
array('Name'=>'Alpha8','Loc'=>'e_vol3','BasketID'=>'81','ProductID'=>'8','Quant'=>'1'),
-
array('Name'=>'Gamma21','Loc'=>'e_vol4','BasketID'=>'81','ProductID'=>'21','Quant'=>'1'),
-
);
-
-
-
foreach ($catalog as &$department) {
-
foreach($cartitems as $basket) {
-
if ($department['ProductID'] == $basket['ProductID']) {
-
$department['InBasket'] = 1;
-
}
-
}
-
}
-
print_r($catalog);
-
-
Array (
-
[0] => Array ( [ProductID] => 2 [Name] => Alpha [DepID] => 2 [InBasket] => 1 )
-
[1] => Array ( [ProductID] => 6 [Name] => Alpha [DepID] => 2 [InBasket] => 1 )
-
[2] => Array ( [ProductID] => 7 [Name] => Alpha [DepID] => 2 [InBasket] => 0 )
-
[3] => Array ( [ProductID] => 8 [Name] => Alpha [DepID] => 2 [InBasket] => 1 )
-
[4] => Array ( [ProductID] => 9 [Name] => Alpha [DepID] => 2 [InBasket] => 0 )
-
)
Thanks for your help and input, and I'm sure I will be back with more questions.
Kind regards.
John,
Not sure if you are still looking at this thread. If you are -
1) Sorry, I should have tested my code before I posted it to make sure it was correct
2) You are still not using an associative array (look at your own results above the output of the array is indexed 0 - 4)
3) Run my code below. I have tested it and it works (look at the output of the last print statement and notice the array element keys are listed). Just click "select" and ctrl-c to copy code. I have included in the code the expected output at each print statement. -
<?php
-
$catalog = array(
-
array('ProductID'=>2,'Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
array('ProductID'=>6,'Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
array('ProductID'=>7,'Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
array('ProductID'=>8,'Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
array('ProductID'=>9,'Name'=>'Alpha','DepID' =>2,'InBasket'=>'0')
-
);
-
echo "<br/><b>Your array setup --- Notice catalog array is indexed</b><br/>";
-
print_r($catalog);
-
/*Ouput of array shows it is an indexed array
-
Array (
-
--------------------------------------------------------------------
-
[0] => Array ( [ProductID] => 2 [Name] => Alpha [DepID] => 2 [InBasket] => 0 )
-
[1] => Array ( [ProductID] => 6 [Name] => Alpha [DepID] => 2 [InBasket] => 0 )
-
[2] => Array ( [ProductID] => 7 [Name] => Alpha [DepID] => 2 [InBasket] => 0 )
-
[3] => Array ( [ProductID] => 8 [Name] => Alpha [DepID] => 2 [InBasket] => 0 )
-
[4] => Array ( [ProductID] => 9 [Name] => Alpha [DepID] => 2 [InBasket] => 0 ) )
-
-
*/
-
$cartitems = array(
-
array('Name'=>'Alpha2','Loc'=>'e_vol1','BasketID'=>'81','ProductID'=>'2', 'Quant'=>'1'),
-
array('Name'=>'Beta4','Loc'=>'e_vol2','BasketID'=> '81','ProductID'=>'6', 'Quant'=>'1'),
-
array('Name'=>'Alpha8','Loc'=>'e_vol3','BasketID'=>'81','ProductID'=>'8', 'Quant'=>'1'),
-
array('Name'=>'Gamma21','Loc'=>'e_vol4','BasketID' =>'81','ProductID'=>'21','Quant'=>'1')
-
);
-
-
foreach ($catalog as &$department) {
-
foreach($cartitems as $basket) {
-
if ($department['ProductID'] == $basket['ProductID']) {
-
$department['InBasket'] = 1;
-
}
-
}
-
}
-
echo "<br/><br/><b>Notice catalog array is indexed</b><br/>";
-
print_r($catalog);
-
/*Output shows an indexed array not an associtive array
-
Notice catalog array is indexed
-
Array (
-
--------------------------------------------------------------------
-
[0] => Array ( [ProductID] => 2 [Name] => Alpha [DepID] => 2 [InBasket] => 1 )
-
[1] => Array ( [ProductID] => 6 [Name] => Alpha [DepID] => 2 [InBasket] => 1 )
-
[2] => Array ( [ProductID] => 7 [Name] => Alpha [DepID] => 2 [InBasket] => 0 )
-
[3] => Array ( [ProductID] => 8 [Name] => Alpha [DepID] => 2 [InBasket] => 1 )
-
[4] => Array ( [ProductID] => 9 [Name] => Alpha [DepID] => 2 [InBasket] => 0 ) )
-
-
-
*/
-
-
/*
-
----------------------------------------------------
-
Catalog array built as an associtive array
-
----------------------------------------------------
-
*/
-
$catalog = array(
-
'2' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
'6' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
'7' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
'8' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
'9' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0')
-
);
-
echo "<br/><br/><b>Associtive Array --- Catalog array before update</b><br/>";
-
print_r($catalog);
-
-
$cart = array(
-
array('Name'=>'Alpha2','Loc'=>'e_vol1','BasketID'=>'81' ,'ProdID'=>'2','Quant'=>'1'),
-
array('Name'=>'Beta4','Loc'=>'e_vol2','BasketID'=>'81' ,'ProdID'=>'4','Quant'=>'1'),
-
array('Name'=>'Alpha8','Loc'=>'e_vol3','BasketID'=>'81' ,'ProdID'=>'8','Quant'=>'1'),
-
array('Name'=>'Gamma21','Loc'=>'e_vol4','BasketID'=>'81','ProdID'=>'21','Quant'=>'1'),
-
);
-
echo "<br/><br/><b>Cart Array</b> <br/>";
-
print_r($cart);
-
-
/*
-
------------------------------------------
-
Example using "for next" and "foreach" loop
-
------------------------------------------
-
*/
-
for ($y = 0, $size = count($cart); $y < $size; $y++)
-
{
-
foreach ($catalog as $productId => $value )
-
{
-
//test if product id is found in catalog. If so update catalog array
-
if ($productId == ($cart[$y]['ProdID']))
-
{
-
$catalog[$productId]['InBasket'] = 1;
-
}
-
}
-
}
-
echo "<br/><br/><b>Associtive Array --- Catalog Array after foreach loop</b><br/>";
-
print_r($catalog);
-
-
/* Output
-
Catalog Array after foreach loop
-
--------------------------------------------------------------------
-
Array (
-
[2] => Array ( [Name] => Alpha [DepID] => 2 [InBasket] => 1 )
-
[6] => Array ( [Name] => Alpha [DepID] => 2 [InBasket] => 0 )
-
[7] => Array ( [Name] => Alpha [DepID] => 2 [InBasket] => 0 )
-
[8] => Array ( [Name] => Alpha [DepID] => 2 [InBasket] => 1 )
-
[9] => Array ( [Name] => Alpha [DepID] => 2 [InBasket] => 0 ) )
-
*/
-
/*re-initilaze catalog array*/
-
$catalog = array(
-
'2' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
'6' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
'7' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
'8' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),
-
'9' => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0')
-
);
-
-
-
/*
-
------------------------------------------
-
Example eliminating one of the "foreach" loop
-
------------------------------------------
-
*/
-
for ($i = 0, $size = count($cart); $i < $size; ++$i)
-
{
-
$productId = $cart[$i]['ProdID'];
-
-
//test if product id is found in catalog. If so update catalog array
-
if (isset($catalog[$productId])){
-
$catalog[$productId]['InBasket'] = 1;
-
}
-
}
-
echo "<br/><br/><b>Associtive Array --- Catalog Array 2 after no foreach loop</b><br/>";
-
print_r($catalog);
-
-
/* Output
-
Catalog Array 2 after eliminating one foreach loop
-
--------------------------------------------------------------------
-
Array (
-
[2] => Array ( [Name] => Alpha [DepID] => 2 [InBasket] => 1 )
-
[6] => Array ( [Name] => Alpha [DepID] => 2 [InBasket] => 0 )
-
[7] => Array ( [Name] => Alpha [DepID] => 2 [InBasket] => 0 )
-
[8] => Array ( [Name] => Alpha [DepID] => 2 [InBasket] => 1 )
-
[9] => Array ( [Name] => Alpha [DepID] => 2 [InBasket] => 0 ) )
-
*/
-
?>
-
Hi Claus
I'm still confused by these associative arrays, these are the two functions I use to extract the data into the 'Cart' and 'Catalog' arrays -
Function GetBasketItems()
-
{
-
//Used to get all the items in the customers basket
-
require '../includes/cxwdb.inc.php';
-
session_start();
-
unset($_SESSION['CartItems']);
-
$BasID = $_SESSION['custDetails']['CustomerID'];
-
$sql = "call procGetAllItems($BasID)";
-
$result = mysqli_query($link, $sql);
-
-
if (!$result)
-
{
-
$error = mysqli_errno($link) . ": " . mysqli_error($link) . "\n";
-
$error1 = $prodID;
-
$error2 = $BasID;
-
include '../err/error.html.php';
-
exit();
-
}
-
if (mysqli_num_rows($result) > 0)
-
{
-
while ($row = mysqli_fetch_array($result))
-
$cItems[] = array(
-
'Name' => $row['Name'],
-
'ProductID' => $row['ProductID'],
-
'Quantity' => $row['Quantity'],
-
'Price' => $row['Price'],
-
'LinePrice' => $row['LinePrice'],
-
'Location' => $row['Location'],
-
'Discount' => $row['Discount'],
-
'BasketID' => $row['BasketID'],
-
'countrytax' => $row['countrytax'],
-
'LineTax' => $row['LineTax']);
-
$_SESSION['CartItems'] = $cItems;
-
return true;
-
}
-
Else {
-
return false;
-
}
-
}
-
-
-
-
Function GetCatalogue($DeptID = 0)
-
{
-
unset($tempcat);
-
//unset($_SESSION['Catalogue']);
-
If ($DeptID > 0)
-
{
-
include '../includes/cxwdb.inc.php';
-
$result = mysqli_query($link, "call procGetCatalogue($DeptID)");
-
if (!$result)
-
{
-
$error = mysqli_errno($link) . ": " . mysqli_error($link) . "\n";
-
$error1 = $prodID;
-
$error2 = $BasID;
-
include '../err/error.html.php';
-
exit();
-
}
-
if (mysqli_num_rows($result) > 0)
-
{
-
while ($row = mysqli_fetch_array($result))
-
$tempcat[] = array(
-
'ProductID' => $row['ProductID'],
-
'Name' => $row['Name'],
-
'DepartmentID' => $row['DepartmentID'],
-
'Price' => $row['Price'],
-
'Location' => $row['Location'],
-
'DepartmentName' => $row['DepartmentName'],
-
'Discount' => $row['Discount'],
-
'InBasket' => $row['InBasket']);
-
Return $tempcat;
-
}
-
}
-
}
-
-
What do I need to do to these to return associative arrays ?
Kind regards
It is in the way you create the array. You use the [] push method to add each row to the array. If you assign the Product Id to the row key then it becomes associative.
Take a look at the code below. I commented out your method of creating the array and inserted the associative array creation method. (CAUTION!!! I did not test - but this is the same way I created the array in the test code).
Remember to access the data in the associative array you need to retrieve the key not the value. You will want to compare the "ProductId" from the cart array (which is indexed) to the "key" of the catalog array. So in the "foreach" loop use this syntax "foreach (array_expression as $key => $value)".
But my suggestion the whole time has been to eliminate that 2nd loop. That is the real advantage of the assoc. array.
Look for my code block above with this code:
" for ($i = 0, $size = count($cart); $i < $size; ++$i)
{
$productId = $cart[$i]['ProdID'];
//test if product id is found in catalog. If so update catalog array
if (isset($catalog[$productId])){
$catalog[$productId]['InBasket'] = 1;
}
}" - if (mysqli_num_rows($result) > 0)
-
{
-
while ($row = mysqli_fetch_array($result))
-
{
-
/*
-
---------------------------------------
-
HERE you are creating an indexed array
-
since you use [] push method to create
-
each row in the array it is indexed.
-
-
The first dimension is indexed. Then
-
within the row you create an assoc array
-
with the key => value pair
-
---------------------------------------
-
$tempcat[] = array(
-
'ProductID' => $row['ProductID'],
-
'Name' => $row['Name'],
-
'DepartmentID' => $row['DepartmentID'],
-
'Price' => $row['Price'],
-
'Location' => $row['Location'],
-
'DepartmentName' => $row['DepartmentName'],
-
'Discount' => $row['Discount'],
-
'InBasket' => $row['InBasket']);
-
-
-
---------------------------------------
-
Here an Assoc. array is created and
-
the Product Id is the row key.
-
-
Each time you loop around a new row is
-
added and it's key is the Product Id
-
---------------------------------------
-
*/
-
$tempcat[$row['ProductID']] = array(
-
'Name' => $row['Name'],
-
'DepartmentID' => $row['DepartmentID'],
-
'Price' => $row['Price'],
-
'Location' => $row['Location'],
-
'DepartmentName' => $row['DepartmentName'],
-
'Discount' => $row['Discount'],
-
'InBasket' => $row['InBasket']);
-
}
-
-
Return $tempcat;
-
}
-
Some times I get a little long winded. The only difference between creating the arrays are
$tempCart[]
and
$tempCart[$row['ProductId']]
In the 2nd method you assign a value to the array element's key. And that value can be alphanumeric ie: $tempCart['Claus'].
Where an indexed array just assigns the next number.
Interestingly if you do this
$tempCart['6'] = 'something';
$tempCart[] = 'something else';
and print out they array you would get
[6] = something
[7] = something else
Hi
When I tried the code -
$tempcat $row['ProductID'] => array(
-
'Name' => $row['Name'],
-
'DepartmentID' => $row['DepartmentID'],
-
'Price' => $row['Price'],
-
'Location' => $row['Location'],
-
'DepartmentName' => $row['DepartmentName'],
-
'Discount' => $row['Discount'],
-
'InBasket' => $row['InBasket']);
-
Return $tempcat;
-
I get the error
Parse error: syntax error, unexpected T_VARIABLE on line xx
In VB I'm only used to one kind of array which has rows and columns i.e array(0 to 5, 0 to 9) and it is filled from a recordset with one command 'GetRows'
Considering my arrays are so small what are the performance issues between associative and indexed arrays are we talking clock cycles here or much more
I am sure there is not a big time difference.
But your error is because you do not have the [ ] for the $tempcat and you use the "=>" instead of "="
you wrote $tempcat $row['ProductID'] => array(
it should be $tempcat[$row['ProductID']] = array(
I suspect you never worked with dictionaries in VB6, then you would have been looking at something similar to assoc. arrays.
If you decided to stick with indexed arrays then you should go back to the for/next looping method.
Hi Claus
Both the for/next and the foreach loops work at the moment and provide what I need. They will not be called thousands of times so I feel that I am losing a lot of time without gain.
Thank you very much for your help and input it was a shame I was such a poor student, however, when time is on my side I will return and have another go at these arrays.
Kind regards.
You were not a poor student. Sorry I did not get the right info to you in a timely manner.
While it is too late to change things now php actually has a number of built in functions that handle arrays. In this case there is a specific function which would have eliminated the need for loops.
John could have used the array_intersect() to compare his two arrays. This would have given him a list of array elements in the catalog array to update with the new value.
Sign in to post your reply or Sign up for a free account.
Similar topics
by: agent349 |
last post by:
First off, I know arrays can't be compared directly (ie: if (arrary1
== array2)). However, I've been trying to compare two arrays using
pointers with no success. Basically, I want to take three...
|
by: Charles Banas |
last post by:
i've got an interesting peice of code i'm maintaining, and i'd like to
get some opinions and comments on it, hopefully so i can gain some
sort of insight as to why this works.
at the top of the...
|
by: chella mani |
last post by:
hi all,
I am developing a tool for scientific application which must be time
and memory efficient,my tool uses 1D,2D and 3D arrays. Is it a good
practice to use 3D arrays in applications or I...
|
by: jacob navia |
last post by:
Has anyone here any information about how arrays can be
formatted with printf?
I mean something besides the usual formatting of each element
in a loop. I remember that Trio printf had some...
|
by: Peteroid |
last post by:
I looked at the addresses in an 'array<>' during debug and noticed that the
addresses were contiguous. Is this guaranteed, or just something it does if
it can?
PS = VS C++.NET 2005 Express...
|
by: Sjoerd |
last post by:
Summary: Use foreach(..) instead of while(list(..)=each(..)).
--==--
Foreach is a language construct, meant for looping through arrays.
There are two syntaxes; the second is a minor but useful...
|
by: motion musso aka: sathia |
last post by:
this is it, how can i get the current index? couldn't figure it out.
thank you
for(i=0;myarray.length<i;i++){
do_something();
//i need the current myarray
}
bye bye
|
by: Bosconian |
last post by:
I'm trying to output the contents of an array of associative arrays in
JavaScript. I'm looking for an equivalent of foreach in PHP.
Example:
var games = new Array();
var teams = new...
|
by: assgar |
last post by:
Hi
Developemnt on win2003 server. Final server will be linux
Apache,Mysql and PHP is being used.
I use 2 scripts(form and process).
The form displays multiple dynamic rows with chechboxs,...
|
by: assgar |
last post by:
Hello
I have changed the process code abit so it receives
the data from the form and ensures the data in array format.
This has eliminated my previous error.
The problem I am experiencing...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new...
| |