Kalaivani Nair
Kalaivani Nair

Reputation: 39

How to display multi dimensional array using foreach

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'])

Upvotes: 0

Views: 2103

Answers (4)

Adil Abbasi
Adil Abbasi

Reputation: 3291

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;
    }
}

Upvotes: 1

Milind
Milind

Reputation: 71

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"]);
 ?>

Upvotes: 1

Chris Schmitz
Chris Schmitz

Reputation: 20940

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.

Upvotes: 1

Rizier123
Rizier123

Reputation: 59681

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

Upvotes: 0

Related Questions