1

Check array print_r() view bellow. I want to get total of only "amount" value. And output should not in array. It should be a simple integer value. So result should be 4+3+9= 16

Array
    (
        [0] => Array
            (
                [id] => 15
                [portfolio_id] => 1
                [stock_id] => 1
                [amount] => 4
                [date] => 04/02/2017
                [created_at] => 2017-04-02 09:04:30
                [updated_at] => 2017-04-02 09:04:30
            )

        [1] => Array
            (
                [id] => 14
                [portfolio_id] => 1
                [stock_id] => 3
                [amount] => 3
                [date] => 04/02/2017
                [created_at] => 2017-04-02 09:03:40
                [updated_at] => 2017-04-02 09:03:40
            )

        [2] => Array
            (
                [id] => 13
                [portfolio_id] => 1
                [stock_id] => 4
                [amount] => 9
                [date] => 04/02/2017
                [created_at] => 2017-04-02 09:03:36
                [updated_at] => 2017-04-02 09:03:36
            )

    )

2 Answers 2

3

Try array_sum(array_column($input, 'amount'));

array_column will return the values of amount key & array_sum calculate the sum of values in the returned array

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

1 Comment

Always consider to add live demo link : eval.in/766287 it's make other clear about your code working.
0

Try this one :

function sum($carry, $item)// summing on amount column of the inner array $item
{
    $carry += $item["amount"];
    return $carry;
}
echo "Amount sum : ".array_reduce($a, "sum");// output : 59

Example :

<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 4/2/2017
 * Time: 11:17 AM
 */

  $array = array
     (
        array("name"=>"Volvo","amount"=>22,"id"=>18),
        array("name"=>"BMW","amount"=>15,"id"=>13),
        array("name"=>"Saab","amount"=>5,"id"=>2),
        array("name"=>"Land Rover","amount"=>17,"id"=>15)
     );

    function sum($carry, $item)
    {
        $carry += $item["amount"];
        return $carry;
    }
    echo "Amount sum : " .array_reduce($array, "sum");// output : 59

Good luck.

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.