从阵列中获得总和

时间:2011-06-28 07:33:05

标签: php

大家好,我希望得到数组元素的总结。超出以下数组。 我希望最终的总和大小加起来。

    Array
(
    [105 - Screama & Merkury - Kiss Me (Ft. Farah).mp3] => Array
        (
            [name] => 105 - Screama & Merkury - Kiss Me (Ft. Farah).mp3
            [time] => 1309246242
            [size] => 5912295
            [hash] => ae6c5dda2b75a4fcbd9f36394f744717
        )

    [106 - The Fives - It's What You Do (Ft. Vanya Taylor).mp3] => Array
        (
            [name] => 106 - The Fives - It's What You Do (Ft. Vanya Taylor).mp3
            [time] => 1309246243
            [size] => 6361223
            [hash] => 8898827f715e88c7c667bcbc716086f6
        )

    [107 - Crazy Cousinz - Funky Anthem (Ft. MC Versatile).mp3] => Array
        (
            [name] => 107 - Crazy Cousinz - Funky Anthem (Ft. MC Versatile).mp3
            [time] => 1309246243
            [size] => 4841021
            [hash] => dce7d5d3b781625f3e74eab58efc3779
        )

    [108 - Funky Dee - Are You Gonna Bang.mp3] => Array
        (
            [name] => 108 - Funky Dee - Are You Gonna Bang.mp3
            [time] => 1309246243
            [size] => 3766429
            [hash] => 6605b648ead22ace8e5ce77e3c53801f
        )

    [109 - Mr M - Dash Down.mp3] => Array
        (
            [name] => 109 - Mr M - Dash Down.mp3
            [time] => 1309246243
            [size] => 4099700
            [hash] => 1dcb8a77de83ec0315fc4431ff31f311
        )

    [110 - S-X - Woooo.mp3] => Array
        (
            [name] => 110 - S-X - Woooo.mp3
            [time] => 1309246243
            [size] => 3364615
            [hash] => 5069b5956c99bcf468bc3fd00178cc22
        )

    [111 - Lil Silva - Different VIP.mp3] => Array
        (
            [name] => 111 - Lil Silva - Different VIP.mp3
            [time] => 1309246244
            [size] => 4019543
            [hash] => 8b73799089a8a8e64cdff8436fa8c446
        )

    [crossdomain.xml] => Array
        (
            [name] => crossdomain.xml
            [time] => 1309245738
            [size] => 216
            [hash] => 3cb3c78f77460e93c87faec3b50a8434
        )

)

我想加上所有尺寸的键。我怎么能这样做我正在寻找一个使用array_sum,但现在不知道如何更改数组只显示大小键任何帮助请。

2 个答案:

答案 0 :(得分:3)

$totalSize = 0;
foreach($yourarray as $file => $attr) {
    $totalSize += (int) $attr['size'];
}

答案 1 :(得分:1)

PHP5.3解决方案

$totalSize = array_reduce($array, function ($currentTotalSize, $attr) {
  return $currentTotalSize + $attr['size'];
}, 0);

$totalSize = array_sum(array_map(function ($attr) {
  return $attr['size'];
}, $array));

第一个对于“foreach”循环或多或少是一个不同的符号,但应该稍微(可忽略不计?)更快,对于熟悉函数式编程的用户来说,这很容易理解。

第二个是“天真的方法”,首先提取所有条目的大小然后总结。