【问题标题】:Storing array in session variable and retrieving it using foreach in codeigniter将数组存储在会话变量中并在 codeigniter 中使用 foreach 检索它
【发布时间】:2014-12-29 06:29:26
【问题描述】:

这是我在控制器中的代码

class placeorder_ajax extends CI_controller
{
 function __construct()
 {
    parent::__construct();
 }

//change text to check line endings
//new line endings

function index()
{       
//echo "hii";
//echo "<script>alert('dasdas');</script>";


//unset($_SESSION['cart']);
$data = array('product_id'=>$this->input->post('product_id'),
                'quantity'=>$this->input->post('quantity'),
                'unit'=>$this->input->post('unit'),
                'unit_rate'=>$this->input->post('unit_rate'));

                $this->session->set_userdata($data);

                    print_r($data);
?>
<table>
<tr>
<th>Item Name</th>
<th>Quantity</th>
<th>Amount</th>
<th>Action</th>
</tr>
<?php
$i=0;
foreach($_SESSION['cart'] as $cart)
{
    //echo "<pre>"; print_r($cart); echo "</pre>";
    $product_name = $this->db->query("SELECT product_name FROM product WHERE 
 product_id='".$cart['product_id']."'");
    echo "<tr>";
    echo "<td>".$product_name."</td>";
    echo "<td>".$cart['quantity']."</td>";
    echo "<td>".$cart['unit']."</td>";
    echo "<td>".$cart['unit_rate']."</td>";
    echo "<td><a href='javascript:void(0)' rownum='".$i."' class='remove_from_cart'><img  
 src='assets/img/delete.png'/></a></td>";
    echo "</tr>";
    $i++;
 }
?>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table><?php
  }   
  }
  }

我不知道如何将该数组存储在 codeigniter 中的会话变量中并使用 foreach 循环检索它?它给出了错误未定义变量 _SESSION 和为 foreach() 提供的无效参数。那么我该如何解决这个问题?

我在 codeigniter 中这样做

如何将该数组存储在会话变量中并使用 foreach 检索它?

【问题讨论】:

  • 有什么问题?
  • 我不知道如何在会话中存储该数组以及如何使用 foreach 循环检索该数组值
  • can't get it working 是什么意思?有什么错误吗?
  • @KedarB :在这里查看如何在会话中存储数据 - ellislab.com/codeigniter/user-guide/libraries/sessions.html
  • @Napster 我做了这个 $this->session->set_userdata($data);但是我在哪里存储它以及如何检索它?

标签: php codeigniter session


【解决方案1】:

尝试做这样的事情

$myarray =  $_POST;
$_SESSION['myarray_insession'] = $myarray;

或者

$myarray = array('product_id'=>$this->input->post('product_id'),
                'quantity'=>$this->input->post('quantity'),
                'unit'=>$this->input->post('unit'),
                'unit_rate'=>$this->input->post('unit_rate'));


$_SESSION['myarray_insession'] = $myarray;

然后像foreach一样使用

foreach($mysession as $row=>$value){

    }

【讨论】:

    【解决方案2】:

    您的数组是一个关联数组。因此,使用 foreach 循环将其打印为键值对

    foreach($_SESSION['cart'] as $key => $value) {
    
      //$key will be product_id, quantity etc
      //$value will be corresponding values
      echo "key: $key<br />value: $value";
    
      //just for formatting the output
      //this will just insert one more break
      echo "<br />";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多