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!

3
  • stock_id at index 0 and quantity index at 1 will remain same ? Commented May 10, 2015 at 9: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. Commented May 10, 2015 at 10:11
  • @SonDang, have you seen my answer? Commented May 15, 2015 at 18:26

1 Answer 1

0

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

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.