Looping through PHP arrays

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

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

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

    Comment

    • Claus Mygind
      Contributor
      • Mar 2008
      • 571

      #17
      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_expressi on 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;
      }
      }
      "


      Code:
      		    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;
      			}
      Last edited by Claus Mygind; Aug 6 '12, 01:12 PM. Reason: tested and corrected code

      Comment

      • Claus Mygind
        Contributor
        • Mar 2008
        • 571

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

        Comment

        • john garvey
          New Member
          • Jan 2011
          • 50

          #19
          Hi

          When I tried the code
          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

          Comment

          • Claus Mygind
            Contributor
            • Mar 2008
            • 571

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

            Comment

            • john garvey
              New Member
              • Jan 2011
              • 50

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

              Comment

              • Claus Mygind
                Contributor
                • Mar 2008
                • 571

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

                Comment

                Working...