2011-06-16 158 views
0
$cart = $_SESSION['cart']; 
    if ($cart) { 
     $items = explode(',',$cart); 

      //what should i do next?? the value of $items is 4,4,2,2,2,4 
+0

您应该首先在会话中存储*数组*,而不是字符串。使事情变得更简单。 – deceze 2011-06-16 07:35:00

回答

2

为了得到阵列无需重复使用array_unique()

   $cart = $_SESSION['cart']; 
        if ($cart) { 
         $items = explode(',',$cart); 
       $unique_items=array_unique($items); // gives 4,2 


    $result_array=array(); 

     foreach($unique_items as $uni_item) 
     { 
      $item_occurence_count=0; 
      $totalvalue=0; 

     foreach($items as $item) 
      { 
      $item_value=$item; 
      $totalvalue+=$item_value; 
      if($item==$uni_item) 
       { 
        ++$item_occurence_count; 
        $result_array[$uni_item]=$item_occurence_count; 
       } 
      } 
     } 
print_r($result_array); // gives Array ([4] => 3 [2] => 3) 

希望这是需要什么。

+0

tnx男人!你的男人。 =)保持良好=) – yohdaman 2011-06-16 08:14:07

1

我认为你正在寻找array_count_values来计算数组中的值。

+0

它会给我相同的值的总数?如4的值等于3,2等于3? TNX。也许必须读取array_count_values。 – yohdaman 2011-06-16 07:36:51

+0

@yohdaman:查看文档中的示例。 – 2011-06-16 08:07:15

+0

@yohdaman - 这正是array_count_values所做的。 – borrible 2011-06-16 08:23:20