0

enter image description here
Above is what I'm trying achieve in my code.

*P=Product

Below is my code. All I need to do is to display the 'id' as well as 'qty' using foreach.Now it only displays key 'id' and it's value.

I tried

$_SESSION['items'][]=array('id'=>$id,'qty'=>$qty); 

instead of

 $_SESSION['items']=array('id'=>$id,'qty'=>$qty); 

BUT I'm getting this error:Problem with: Fatal error: [] operator not supported for string..

PHP

<?php
session_start();
?>
<?php

 $id=$_GET['id'];
 $qty=$_GET['qty'];


$_SESSION['items']=array('id'=>$id,'qty'=>$qty);
print_r($_SESSION['items']);
foreach($_SESSION['items'] as $items=>$value)
{
    echo $items;

    echo $value;


}

?>

Edited :

I manage to solve the issue. However now,I'm trying to include the above for each product. I mean,

I'm getting the data like this:

$id = $_GET['id'];
$qty = $_GET['qty'];
$product_id=$_GET['product_id'];

//store details inside session

$_SESSION['items'][]= array('id'=>$id,'qty'=>$qty,'product_id'=>$product_id);
print_r($_SESSION['items']);
$item_id= explode(',',$_SESSION['items']['id']);
$item_qty= explode(',',$_SESSION['items']['qty']);
$item_product= explode(',',$_SESSION['items']['product_id']);

//retrive info from database

mysql_select_db($database_wedding_conn, $wedding_conn);
$select="SELECT tbl_additional_info.*,tbl_productscontents.* FROM 

tbl_additional_info,tbl_productscontents WHERE tbl_additional_info.productid='$product_id AND tbl_additional_info.product_id=tbl_productscontents.product_id GROUP BY tbl_productscontents.productid'";

$result=mysql_query($select)or die(mysql_error());

THis is how it displays in table

<table>
    <tr>
        <th>Product</th>
        <th>Size</th>
        <th>Unit Price</th>
        <th>Quantity</th>
        <th>Amount</th>
    </tr>
    <?php
    foreach($item_product as $p=>$p_value)
         {
    ?>
    <tr>
      <td valign="top">
        <?php
        echo $p;
        echo $p_value;
        ?>
      </td>
      <td>
        <table>

        <?php
        foreach($item_id as $i)
         {
             ?>
             <tr>
                <td>
            <?php  echo $i;?>
               </td>
            </tr>
             <?php
         }
        ?>
        </table>
      </td>
      <td>
        <?php
        foreach($item_qty as $q)
         {
             //unit price
            // echo $q;
         }
        ?>
      </td>
      <td>
      <table>

        <?php
        foreach($item_qty as $q)
         {
             ?>
             <tr>
                <td>
            <?php  echo $q;?>
               </td>
            </tr>
             <?php
         }
        ?>
        </table>
      </td>
      <td>
        <?php
        foreach($item_qty as $q)
         {
             //amount
             //echo $q;

         }
        ?>
      </td>
    </tr>
    <?php
        }
    ?>
</table>

Question: How to I display all the product stored in the session? The for each loop only shows one product.It doesn't add more as it shows in print_r($_SESSION['items'])

4 Answers4

1

What you're working with is an associative array and it's only one dimension. It's associative because rather than access the values by an index number (i.e. an index array) you can access them by an association which is the string value you're giving it (i.e. the 'id' and the 'qty').

If all you're doing is trying to output the value of those assoications, you can do so without the foreach loop:

echo $_SESSION['items']['id'];
echo $_SESSION['items']['qty'];

What you're doing here is saying: "In the associative array $_SESSION, give me the value for the key items and then in it's associative array give me the key id. Repeat the same but give me the key qty"

EDIT:

So if you're expecting a query string containing array values, for example:

http://example.com?id[]=1&id[]=2&qty[]=10&qty[]=20

You could access the values with a for loop instead of a foreach:

<?php

 $id=$_GET['id'];
 $qty=$_GET['qty'];

for($i=0;$i < count($id) ; $i++){
   echo "ID: " . $id[$i] . " has QTY: " . $qty[$i] . "<br />";
}

?>

This assumes you'll always have the same number of id values as qty values, but you could add logic in to handle an uneven grouping.

Chris Schmitz
  • 20,160
  • 30
  • 81
  • 137
  • Thanks alot.I tried your idea and it worked. However Now I iterate id and qty inside product_id as shown in the edited part. But the product_id doesn't increment.Simply showing one product at all the time. It's a shopping cart that I'm creating. So shopping cart should allow multiple products stored in it. Can you help me with it pls..Thanks – Kalaivani Nair Nov 13 '14 at 06:31
  • Could you include the actual query string you're expecting in the browser so we can see the product info coming into the `$_GET` variable? – Chris Schmitz Nov 13 '14 at 06:47
  • test_site/shopping_cart.php?id=17,18&qty=45,23&product_id=3# – Kalaivani Nair Nov 13 '14 at 07:05
  • ,I have added a picture to elaborate what I mean. – Kalaivani Nair Nov 13 '14 at 07:42
  • I can't elaborate at the moment (I'm at work) but to get the grid that you're wanting you def need a multi dimensional array. It would be creating a base array, e.g. `$table = array();` and then pushing your other arrays into it during your for loop, e.g. `$table[] = array( 'id' => $id[$i], 'qty' => $qty[$i], 'product_id' => $product_id[$i]);`. I'll try to elaborate more in my answer later. – Chris Schmitz Nov 13 '14 at 15:55
1

For this type of assingment

$_SESSION['items'][]=array('id'=>$id,'qty'=>$qty); 

use nested foreach like,

foreach($_SESSION['items'] as $items=>$values)
{
    foreach($values as $item=>$value)
    {
        echo $item.": ";
        echo $value."\n";
    }
}

Output Example:

id: test_id
qty: test_qty

For the second issue, use foreach like below instead of explode it will provide clean array for iteration on view or for database query.

$item_product = array();
$item_id = array();
$item_qty = array();
foreach($_SESSION['items'] as $items=>$values)
{
    foreach($values as $item=>$value)
    {
        if($item == 'id');
            $item_id[] = $value;

        else if($item == 'qty');
            $item_qty[] = $value;

        else if($item == 'product');
            $item_product[] = $value;
    }
}
Adil Abbasi
  • 3,161
  • 1
  • 40
  • 35
  • If you are sure your session contains more than 1 items data then instead of using explode just save them in array like in the above nested loop example instead of echo code like... if($item == 'id'){$product_id[]=$value;} .... for each item key that will give a clean array for loop iterations. – Adil Abbasi Nov 13 '14 at 07:02
  • if u don't mind can u show an example pls..I'm not sure how to do it – Kalaivani Nair Nov 13 '14 at 07:08
  • Edited solution, please up vote comment if it helped. – Adil Abbasi Nov 13 '14 at 07:20
1

If you would like to display value multidimensional array then code below code is usefull but there is no need of for each loop Kalaivani.

And if you want to display data from database or multiple record then foreach loop is useful see bellow example

  <?php 

  $sql="write here your select query and pass record to $sql";//pass multiple value from database

                       **OR**

  $sql= array('id'=>$id,'qty'=>$qty);//pass multiple value from array
  session_name("items");
  $id=$_GET['id'];
  $qty=$_GET['qty'];
  $_SESSION["items"]["id"]=$id;
  $_SESSION["items"]["qty"]=$qty;
  print_r($_SESSION["items"]);
 ?>
Milind
  • 71
  • 8
0

This should work:

<?php

    session_start();

    //temp
    $_GET['id'] = 7;
    $_GET['qty'] = "test";

    $id = $_GET['id'];
    $qty = $_GET['qty'];

    $_SESSION['items'] = array('id'=>$id,'qty'=>$qty);

    foreach($_SESSION['items'] as $k => $v) 
        echo "Key: " . $k . " Value: " . $v . "<br />";

?>

Output:

Key: id Value: 7
Key: qty Value: test
Rizier123
  • 58,877
  • 16
  • 101
  • 156