最后一次迭代值留在数组中

时间:2017-08-18 07:20:42

标签: php codeigniter

  if ($cart = $this->cart->contents())
  {
        foreach ($cart as $item){
            $order_detail = array(
                'res_id'        =>$this->session->userdata('menu_id[]'),
                'customer_id'   =>$coustomers,
                'payment_id'    =>$payment,
                'name'          => $item['name'],
                'productid'     => $item['id'],
                'quantity'      => $item['qty'],
                'price'         => $item['price'],
                'subtotal'      => $item['subtotal']
            );  
            }
            print_r($order_detail); exit;

foreach循环结束时,只剩下最后一个迭代值。我需要将所有值都放在数组中。

3 个答案:

答案 0 :(得分:2)

更改此行

Route::get('contacts/new', 'ContactController@new_contact');
Route::get('contacts/{id}', 'ContactController@get_contact');

$order_detail = array(..);

答案 1 :(得分:2)

因为order_detail每次都会覆盖。使用数组而不是简单变量。

$order_detail = array();
if ($cart = $this->cart->contents())
  {
    foreach ($cart as $item){
        $order_detail[] = array(
            'res_id'        =>$this->session->userdata('menu_id[]'),
            'customer_id'   =>$coustomers,
            'payment_id'    =>$payment,
            'name'          => $item['name'],
            'productid'     => $item['id'],
            'quantity'      => $item['qty'],
            'price'         => $item['price'],
            'subtotal'      => $item['subtotal']
        );  
      }
print_r($order_detail); exit;

答案 2 :(得分:1)

试试这个 首先定义数组

$order_detail=array();

array_push($order_detail, array(...));

数组声明必须在循环之外。