0

following is my array

Array(
[id] => 1
[user_id] => 30
[list] => Array
    (
        [0] => Array
            (
                [id] => 1
                [card_id] => 6
                [amount] => 400
            )

        [1] => Array
            (
                [id] => 2
                [card_id] => 3
                [amount] => 500
            )

    )
)

from above array i want to get values of amount key which is in list key. i want to store that values in one variable. P.S : In list array it will have multiple arrays

Edit: there should be sum of all amount in output. for example from above array sum woulld be 900 is $total_amount = 900

sangRam
  • 315
  • 4
  • 17
  • You should provide expected output – MorganFreeFarm Jul 31 '19 at 20:39
  • thanks for your comment. Please see question i have edit it. – sangRam Jul 31 '19 at 20:45
  • You should provide your own best effort, so we can help you help yourself – lovelace Jul 31 '19 at 20:46
  • Please note that you are expected to make an attempt to achieve your desired result yourself. If you have not done so, please take some time to do so now. If you _have_, please include your attempt within your question, along with the result and how it differs from what you want. – Patrick Q Jul 31 '19 at 20:46
  • thank you everybody for your valuable comments, in future if i have any question i will post with code which i have try and i also look that it should be not duplicate question. – sangRam Jul 31 '19 at 21:43

2 Answers2

2

One liner with array_column and array_sum;

echo array_sum(array_column($array["list"], 'amount')); // 900

See online: https://3v4l.org/EsvJO

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
1

Here is what you want, simple foreach:

$array = [
"id" => 1,
"user_id" => 30,
"list" => [
            [
                "id" => 1,
                "card_id" => 6,
                "amount" => 400,
            ],

        [

                "id" => 2,
                "card_id" => 3,
                "amount" => 500,
        ]

    ]
];

$totalAmount = 0;

foreach ($array["list"] as $array){
  $totalAmount += $array["amount"];
}

var_dump($totalAmount);

Result: 900

MorganFreeFarm
  • 3,811
  • 8
  • 23
  • 46