2011-06-28 118 views
-1

大家好,我期待得到數組元素的總和。超出以下數組。 我想要最後的總和大小關鍵加起來。從數組中獲得總和

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但現在不要如何更改數組只是顯示大小關鍵任何幫助請。

回答

3
$totalSize = 0; 
foreach($yourarray as $file => $attr) { 
    $totalSize += (int) $attr['size']; 
} 
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'環,但應該稍微快一點(可以忽略不計?),熟悉函數式編程的用戶可以輕鬆理解。

第二個是「天真的方法」,首先提取所有條目的大小,然後總結它。

+0

$ totalSize不會超出範圍嗎? – Phliplip

+0

我應該給他們不同的名字。表達式前的$ totalSize和作爲閉包參數的$ totalSize是不同的變量。 – KingCrunch

+0

是的你說得對,以前沒有用過'array_reduce()'。只是在[php.net/array_reduce](http://dk.php.net/array_reduce)上做了一個readup - 我每天都在學習,我喜歡它! – Phliplip