php返回在二维会话数组中具有相同元素的总数

时间:2016-12-23 06:38:39

标签: php arrays count

我有一个包含以下元素的购物车会话:

的print_r($ _ SESSION [ '购物']);

Array
(
    [0] => Array
        (
            [p_name] => X-Dot Motorbike Helmet G88 + Bogo Visor (Test)
            [p_code] => 2102649
            [p_id] => 12332
            [p_price] =>  1.60
            [p_seller] => 230002
            [p_alt-variation-1] => Red
            [p_alt-variation-2] => L - 1.60-36
            [p_qty] => 1
        )

    [1] => Array
        (
            [p_name] => Salt and Lemon Candy (20 Packs/Carton)
            [p_code] => 3443268
            [p_id] => 11654
            [p_price] => 1.20
            [p_seller] => 230002
            [p_qty] => 1
        )

    [2] => Array
        (
            [p_name] => Romoss Rolink Hybrid Premium Cable
            [p_code] => TEST421
            [p_id] => 10670
            [p_price] => 13.90
            [p_seller] => 230001
            [p_qty] => 1
        )

)

[p_seller]所示,我想将相同的p_seller值分组并返回数字:

  

通过数组(230002)返回 2 ,然后返回 1   数组(230001)

我该怎么做?

3 个答案:

答案 0 :(得分:1)

也许你必须尝试这个代码

<?php

$array = array(
    array(
        'p_name' => "X-Dot Motorbike Helmet G88 + Bogo Visor (Test)",
        'p_seller' => '230002',
        'last_name' => 'Doe',
    ),
    array(
        'p_name' => "X-Dot Motorbike Helmet G88 + Bogo Visor (Test)",
        'p_seller' => '230002',
        'last_name' => 'Doe',
    ),
    array(
        'p_name' => "X-Dot Motorbike Helmet G88 + Bogo Visor (Test)",
        'p_seller' => '230001',
        'last_name' => 'Doe',
    )
);

$result = array_count_values(array_column($array, 'p_seller'));
   arsort($result);// not neccesary
   echo "<pre>";print_r($result);exit;
?>

<强>输出

Array
(
    [230002] => 2
    [230001] => 1
)

答案 1 :(得分:0)

如果您知道数组indexes将始终相同,那么您可以简单地对值进行求和。

尝试

echo $_SESSION['cart'][1]['p_seller'] + $_SESSION['cart'][2]['p_seller'];

动态

您可以将array_sumforeach循环

一起使用

尝试

foreach ($_SESSION['cart'] as $val)
{
    if( isset($val['p_seller']) )
        $total[] = $val['p_seller'];
}
if( isset($total) && is_array($total) )
{
    $total = array_sum($total);
    echo $total;
}

更新1

根据我的理解,您只想echo在INDEX p_seller中找到的值。

尝试

$i = 0;
foreach ($_SESSION['cart'] as $val)
{
    if( isset($val['p_seller']) )
    {
        echo ++$i.' - '.$val['p_seller']."<br >";
    }
}

答案 2 :(得分:0)

foreach ($_SESSION['cart'] as $Arrvalues){
  $total+= $Arrvalues['p_seller'];
}
echo $total;

输出:690005