Search code examples
phpmultidimensional-arrayarray-key

How to get values of array element from key


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


Solution

  • One liner with array_column and array_sum;

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

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