如何获取数组的值并获取数组中相同值的总数?
问题描述:
$cart = $_SESSION['cart'];
if ($cart) {
$items = explode(',',$cart);
//what should i do next?? the value of $items is 4,4,2,2,2,4
答
为了得到阵列无需重复使用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
您应该首先在会话中存储*数组*,而不是字符串。使事情变得更简单。 – deceze 2011-06-16 07:35:00