1

I have below $test array

        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
        )

)

and to sum same stock_id keys to one, i use below functions:

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"); 

and the result went well like below:

$sum_same_stock_id:

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

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

)

So the question here is, I wanted to pass an dynamic keys values not just fixed values stock_id & quantity in sum function above. Have tried variety ways but still can't figured out the way. And can we put those functions into class as well?

Any advise is appreciated!

SonDang
  • 1,468
  • 1
  • 15
  • 21
  • `stock_id` at index `0` and `quantity` index at `1` will remain same ? – Noman May 10 '15 at 09:31
  • No, for example if stock_id & quantity name in beginning array has changed to different names like "amount" & "stock_code". And then in sum function, I just need to input dynamic variable that is like function sum($array, $key, $amount, $id), where $amount & $id are "amount" & "stock_code" name rather than manually replace "amount" & "stock_code" repeatedly inside "sum" function. – SonDang May 10 '15 at 10:11
  • @SonDang, have you seen my answer? – splash58 May 15 '15 at 18:26

1 Answers1

0

Maybe you can use the "use" function for the callback?

See https://www.php.net/manual/en/functions.anonymous.php

Disu
  • 113
  • 10