1

我有以下$test数组

        Array
(
    [0] => Array
        (
            [quantity] => 3
            [stock_id] => _PHONE
        )

    [1] => Array
        (
            [quantity] => 3
            [stock_id] => 102
        )

    [2] => Array
        (
            [quantity] => 4
            [stock_id] => _PHONE
        )

    [3] => Array
        (
            [quantity] => 3
            [stock_id] => 102
        )

    [4] => Array
        (
            [quantity] => 4
            [stock_id] => _PHONE
        )

    [5] => Array
        (
            [quantity] => 6
            [stock_id] => _PHONE
        )

    [6] => Array
        (
            [quantity] => 2
            [stock_id] => 102
        )

)

并将相同的 stock_id 键相加为一个,我使用以下函数:

function sum($array, $key){
    isset($array[$key['stock_id']]) ? $array[$key['stock_id']]['quantity'] += $key['quantity'] : $array[$key['stock_id']] = $key;  
    return $array;
};

//merge same stock_id and sum the quantity same stock id
$sum_same_stock_id = array_reduce($test, "sum"); 

结果如下:

$sum_same_stock_id:

Array
(
    [_PHONE] => Array
        (
            [quantity] => 17
            [stock_id] => _PHONE
        )

    [102] => Array
        (
            [quantity] => 8
            [stock_id] => 102
        )

)

所以这里的问题是,我想在上面的函数stock_id中传递一个动态键值而不仅仅是固定值。尝试了各种方法,但仍然无法弄清楚方法。我们也可以将这些函数放入类中吗?quantitysum

任何建议表示赞赏!

4

0 回答 0