Link to home
Start Free TrialLog in
Avatar of weikelbob
weikelbobFlag for United States of America

asked on

How does this foreach loop work?

How does a foreach loop work?

My array is SESSION['cart'][] = ...
ASKER CERTIFIED SOLUTION
Avatar of maUru
maUru

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of weikelbob

ASKER

When do you use an associative array?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I'm still unclear. Can you give me an example of an associative array that doesn't involve a database?
An associative array is no different from any other array, except that you refer to its contents using strings instead of numbers.

$numerical_array = array();
$numerical_array[0] = 'Alpha';
$numerical_array[1] = 'Beta';
$numerical_array[2] = 'Gamma';

$associative_array = array();
$associative_array['A'] = 'Alpha';
$associative_array['B'] = 'Beta';
$associative_array['C'] = 'Gamma';

It's just however you prefer to access the data. There are a lot of examples where numerical arrays are practically impossible because you, as a PHP programmer, need to keep track of each piece of data by name. There are other cases where numerical arrays are absolutely required because you need to iterate over the array or whatnot. Oh, and arrays can have both numerical and associative indeces, of course. And by the way, associative indeces are case sensitive, so $associative_array['A'] is different from $associative_array['a'].
And of course, these two commands will do exactly the same thing:

1.    echo $associative_array['Abc'];

2.    $string = 'Abc';
       echo $associative_array[$string];
SOLUTION
Avatar of Roonaan
Roonaan
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks guys. Roonaan, I'm saving a description, a quantity, and a shipping amount for each purchased item in my sessions. I assume I should use associative arrays. What's the best way to organize this?
I think something like:

$_SESSION['cart']['itemid'] = array('id' => 'itemid', 'quantity' => 'number', 'description' => 'text', 'price' => 0.00, 'shipping' => 0.00);

-r-

Avatar of maUru
maUru

using roonaans code, you can access data by:

echo $_SESSION['cart']['id']; //echos id
echo $_SESSION['cart']['quantity']; //echos quantity
etc.

also one little typo in his code: 'quantity' => 'number' should be 'quantity' => 0
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
For sorting multidimensional arrays I often use a class:

<?php


class columnSorter {
  var $column = '';
  function columnSorter($column) {
    $this->column = $column;
  }
  function sort($a, $b) {
    $a = $a[$this->column];
    $b = $b[$this->column];
    if($a == $b) return 0;
    return $a > $b ? 1 : -1;
  }
}

$array[] = array('a' => 1, 'b' => 2, 'c' => 8);
$array[] = array('a' => 2, 'b' => 1, 'c' => 7);
$array[] = array('a' => 3, 'b' => 0, 'c' => 6);
$array[] = array('a' => 4, 'b' => 1, 'c' => 5);
$array[] = array('a' => 5, 'b' => 2, 'c' => 4);
$array[] = array('a' => 6, 'b' => 1, 'c' => 3);
$array[] = array('a' => 7, 'b' => 0, 'c' => 2);
$array[] = array('a' => 8, 'b' => 1, 'c' => 1);

$sort = new columnSorter('a');
usort($array, array($sort, 'sort'));
echo '<pre>'.var_export($array, true).'</pre>';

-r-
Having said that ...

<?php
$an_array = array
      (
      0 => array
            (
            'id' => 1234,
            'quantity' => 12,
            'description' => 'Cheap book',
            'price' => 9.99,
            'shipping' => 2.00,
            ),
      1 => array
            (
            'id' => 4321,
            'quantity' => 21,
            'description' => 'Another Cheap book',
            'price' => 19.99,
            'shipping' => 1.40,
            ),
      );

$a_sort = array();
foreach($an_array as $i_key => $a_data)
      {
      $a_sort[$i_key] = $a_data['description'];
      }
print_r($an_array);
array_multisort($a_sort, $an_array);
print_r($an_array);
?>

produces ...

Array
(
    [0] => Array
        (
            [id] => 1234
            [quantity] => 12
            [description] => Cheap book
            [price] => 9.99
            [shipping] => 2
        )

    [1] => Array
        (
            [id] => 4321
            [quantity] => 21
            [description] => Another Cheap book
            [price] => 19.99
            [shipping] => 1.4
        )

)
Array
(
    [0] => Array
        (
            [id] => 4321
            [quantity] => 21
            [description] => Another Cheap book
            [price] => 19.99
            [shipping] => 1.4
        )

    [1] => Array
        (
            [id] => 1234
            [quantity] => 12
            [description] => Cheap book
            [price] => 9.99
            [shipping] => 2
        )

)

Some concept but requires the extraction of the keys to sort by. Which is probably a lot easier to deal with if your HTML page has sort asc/desc buttons on columns.

You can add descending sort to the array_multisort()

array_multisort($a_sort, $an_array, SORT_DESC);

or ...

<?php
$an_array = array
      (
      0 => array
            (
            'id' => 1234,
            'quantity' => 12,
            'description' => 'Cheap book',
            'price' => 9.99,
            'shipping' => 2.00,
            ),
      1 => array
            (
            'id' => 4321,
            'quantity' => 21,
            'description' => 'Another Cheap book',
            'price' => 19.99,
            'shipping' => 1.40,
            ),
      );


$i_sort_order = SORT_ASC;
if (isset($_GET['orderby']) && in_array($_GET['orderby'], array(SORT_ASC, SORT_DESC)))
      {
      $i_sort_order = intval($_GET['orderby']);
      }

$a_sort = array();
if (isset($_GET['sorton']))
      {
      foreach($an_array as $i_key => $a_data)
            {
            if (isset($a_data[$_GET['sorton']]))
                  {
                  $a_sort[$i_key] = $a_data['description'];
                  }
            else
                  {
                  $a_sort[$i_key] = NULL;
                  }
            }
      }
print_r($an_array);
array_multisort($a_sort, $an_array, $i_sort_order);
print_r($an_array);
?>

sort of thing.

Ok. Way too much information!
Wow!, I really appreciate this detailed information. This area is my weakest, it just doesn't register like the rest of PHP does for me. Are there any simple tutorials that I could follow up with to help get this stuff sunk in?

Again, I really appreciate this.

Bob
The trouble with self taught people like me is I don't use tutorials. I use other peoples code to learn from.

Tutorials are always out of context for me.
interesting....
I would take a look at the PHP Manual. It is the only PHP reference book I use.
Wow, I'm going to bookmark this one. It's one of the areas of php that I'm slow with.

Thanks guys.

Bob