2013-03-14 137 views
1

我有一個ID數字的MySQL查詢數組,我嘗試將其添加到已創建的會話數組中。出於某種原因,我的代碼已經在Session Array中添加了一個數組,而不僅僅是將ID號添加到Session中。是什麼導致了這種情況發生?將數組添加到會話數組

這是我的PHP ...

//Find members of this group and create an array to add to cart 
      $deletedgroupmembersquery = "SELECT * FROM groupmember WHERE group_id='$groupid'"; 
      $deletedgroupmembers = mysql_query($deletedgroupmembersquery) or die('SQL Error :: '.mysql_error()); 

      if (mysql_num_rows($deletedgroupmembers) > 0) { 
       $groupmembers = mysql_num_rows($deletedgroupmembers); 
       $cart = array(); 
       while(($deletedmembersrow = mysql_fetch_assoc($deletedgroupmembers))) { 
        $cart[] = $deletedmembersrow['contact_id']; 
       } 

        //Add the array to the cart session 
        if (isset($cart)) { 
        $_SESSION['cart'] = array(); 
        array_push($_SESSION[cart],$cart); 
        } else { 
        } 

這裏是上面的代碼創建會話..

Array ([cart] => Array ([0] => Array ([0] => 1362 [1] => 1371 [2] => 2241)) 

感謝您的幫助。

回答

0

您將$ cart定義爲一個數組,然後將它推入$ _SESSION [cart]中...所以您將數組推入數組中。嘗試是這樣的:

if (!empty($cart)) { 
    $_SESSION['cart'] = array(); 
    foreach ($cart AS $item) { 
    array_push($_SESSION['cart'], $item); 
    } 
} 

你也可以放置array_push你而內(),和前一陣貼$ _SESSION [「購物車」] =陣列()(),它會實現一樣。

+0

你的建議完美的工作,除了它取代了已經存在的數組。我如何將數組添加到購物車數組中已有的值? – Budove 2013-03-14 02:16:20

+0

如果$ _SESSION ['cart']裏面已經有值,則刪除$ _SESSION ['cart'] = array()行。這只是覆蓋無論它可能已經是一個空的數組。 array_push會將新元素推送到數組的末尾,而不管數組中可能已有的元素。 – mchitten 2013-03-14 02:19:07

1

$cart已經是一個數組。當你這樣做時:

array_push($_SESSION[cart],$cart); 

你正在推動它作爲$_SESSION['cart']的子陣列。我想你只是想:

$_SESSION['cart'] = $cart; 
+0

像其他答案一樣,這是否不會替代已經存在的購物車會話?如何將$ cart中的值添加到已經存在的會話數組中? – Budove 2013-03-14 02:17:25

+0

爲什麼你做'$ _SESSION ['cart'] = array();'如果你不想更換已經存在的購物車? – Barmar 2013-03-14 02:20:24