Looping through PHP arrays

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • john garvey
    New Member
    • Jan 2011
    • 50

    Looping through PHP arrays

    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.
    Code:
    $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.
    Code:
    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.
  • Claus Mygind
    Contributor
    • Mar 2008
    • 571

    #2
    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

    Comment

    • john garvey
      New Member
      • Jan 2011
      • 50

      #3
      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

      Comment

      • lyodmichael
        New Member
        • Jul 2012
        • 75

        #4
        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,

        Comment

        • Claus Mygind
          Contributor
          • Mar 2008
          • 571

          #5
          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.

          Code:
          <?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;
                      }
                  }
          ?>

          Comment

          • john garvey
            New Member
            • Jan 2011
            • 50

            #6
            Originally posted by lyodmichael
            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,
            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

            Comment

            • john garvey
              New Member
              • Jan 2011
              • 50

              #7
              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........... ..
              Code:
              //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

              Comment

              • Claus Mygind
                Contributor
                • Mar 2008
                • 571

                #8
                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.
                Code:
                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'] )
                		{
                			[B]//$cart[$x]['InBasket'] = 1;
                			$catalog[$x]['InBasket'] = 1;[/B]
                		}
                	}
                }
                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:
                Code:
                //Connect and get data from MySQL......
                 
                if (mysqli_num_rows($result) > 0)
                {
                        [B]// create an empty array
                        $cItems = array();[/B]
                
                	while ( $row  =  mysqli_fetch_array($result) )
                [B]	{ 
                //to make both dimensions of array assoc. I add "PI" to id because I assume product id is a number.[/B]
                		$cItems[ [B]'PI'.$row['ProductID'][/B] ]  = 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))
                	{
                [B]//in creating the tempcat I just add the "PI" to the product id.[/B]
                		$tempcat[]       = array(
                		'ProductID'      => [B]'PI'.[/B]$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;
                }
                
                /*
                [B]Now you can use the more efficient method of updating your catalog
                [/B]*/
                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.

                Comment

                • Claus Mygind
                  Contributor
                  • Mar 2008
                  • 571

                  #9
                  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.

                  Comment

                  • john garvey
                    New Member
                    • Jan 2011
                    • 50

                    #10
                    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

                    Comment

                    • Claus Mygind
                      Contributor
                      • Mar 2008
                      • 571

                      #11
                      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_expressi on as $value)


                      or

                      2) you can loop through the array and get the key ie "PI2"
                      foreach (array_expressi on as $key => $value). In this version the array key is assigned to $key as in this example

                      Code:
                      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.

                      Code:
                      <?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
                      		------------------------------
                      		*/
                      		[B]foreach ($fieldList as $key => $colName ) [/B]
                      		{
                      			/*
                      			---------------------------------------
                      			if table field/column name found in 
                      			data get results and add to $setString
                      			---------------------------------------
                      			*/
                      			if ( array_key_exists ( [B]$key[/B], $tData ) )
                      			{
                      				/*
                      				---------------------------------------
                      				get current col name
                      				---------------------------------------
                      				*/
                      				$col = $fieldList[[B]$key[/B]];
                      
                      				/*
                      				---------------------------------------
                      				get corrosponding data value, if any
                      				---------------------------------------
                      				*/
                      				$val = $tData[[B]$key[/B]];
                      
                      				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.

                      Code:
                      	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()) {
                      					[B]foreach ( $row as $key => $value )[/B]
                      					{
                      						[B]$value = (empty($value)) ? " ":$value ;[/B]
                      						/*
                      						--------------------------------------------------------
                      						if reference found in $fArray (formatData.php), 
                      						then call associated function. pass 2 for display format
                      						--------------------------------------------------------
                      						*/
                      						if (array_key_exists([B]$key[/B],$fArray))
                      						{
                      							$row[[B]$key[/B]] = call_user_func($fArray[[B]$key[/B]], [B]$value[/B], 2);
                      						}
                      					}
                      					$row = $q->addCalcFields($row);
                      					$aResults[]  = $row;	
                      				}
                      			}else{
                      				$aResults["noRec"] = true;
                      			}
                      		}
                      		$result->free();
                      		return $aResults;
                      	}//end download data to form

                      Comment

                      • john garvey
                        New Member
                        • Jan 2011
                        • 50

                        #12
                        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.

                        Code:
                        $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.

                        Code:
                        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.


                        Code:
                        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.
                        Last edited by Dormilich; Aug 6 '12, 05:25 AM.

                        Comment

                        • Claus Mygind
                          Contributor
                          • Mar 2008
                          • 571

                          #13
                          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.

                          Code:
                          		/*
                          		----------------------------------------------------
                          		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( 
                                      [B]'2'[/B] => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),        
                                  );
                          
                                  $cart[] = array(
                                      array('Name'=>'Alpha2','Loc'=>'e_vol1','BasketID'=>'81' ,'ProdID'=>[B]'2'[/B],'Quant'=>'1'),
                                  );
                          		
                          		OR:
                          		$catalog = array( 
                                      [B]2[/B] => array('Name'=>'Alpha','DepID' =>2,'InBasket'=>'0'),        
                                  );
                          
                                  $cart[] = array(
                                      array('Name'=>'Alpha2','Loc'=>'e_vol1','BasketID'=>'81' ,'ProdID'=>[B]2[/B],'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'),
                                  );                                                                    
                          
                          	/*
                          	------------------------------------------
                          	[B]Example using "foreach" loop[/B]
                          	------------------------------------------
                          	*/
                          	for ($y = 0, $size = count($cart); $y < $size; $y++)
                          	{
                          		[B]foreach[/B] ($catalog as [B]$key[/B] => $value ) 
                          	    {
                          			if ([B]$key[/B] == ($cart[$y]['ProdID']))
                          			{
                          				$catalog[[B]$key[/B]]['InBasket'] = 1;
                          			}
                          		}
                          	}     
                          
                          	/*
                          	------------------------------------------
                          	[B]Example eliminating the "foreach" loop[/B] 
                          	------------------------------------------
                          	*/
                          	for ($i = 0, $size = count($cart); $i < $size; ++$i)
                          	{
                          		[B]$key[/B] = $cart[$i]['ProductID'];
                          		$catalog[[B]$key[/B]]['InBasket'] = 1;
                          	}

                          Comment

                          • john garvey
                            New Member
                            • Jan 2011
                            • 50

                            #14
                            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

                            Code:
                            $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.
                            Last edited by Dormilich; Aug 6 '12, 05:26 AM.

                            Comment

                            • Claus Mygind
                              Contributor
                              • Mar 2008
                              • 571

                              #15
                              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.


                              Code:
                              <?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 ) ) 
                              */
                              ?>

                              Comment

                              Working...