0

我试图在保留键名的同时对键内的值求和,这样我就可以打印出值列表...

这是我拥有的数组:

Array ( 
    [Israel] => Array ( [0] => 3823 [1] => 1358 [2] => 496 [3] => 198 [4] => 134 [5] => 129 [6] => 107 [7] => 93 [8] => 91 [9] => 70 [10] => 60 [11] => 59 [12] => 54 [13] => 50 [15] => 35 [16] => 33 [17] => 33 [18] => 31 [19] => 28 [20] => 28 [24] => 19 [25] => 19 [27] => 18 [28] => 18 [29] => 15 [30] => 15 [31] => 14 [32] => 13 [33] => 13 [36] => 11 [37] => 10 [38] => 10 [39] => 10 [42] => 9 [45] => 7 [46] => 7 [51] => 6 [71] => 4 [72] => 4 [73] => 4 ) 
    [Palestine] => Array ( [14] => 48 ) 
    [Venezuela] => Array ( [21] => 21 [50] => 7 [64] => 5 [95] => 3 ) 
    [(not set)] => Array ( [22] => 20 ) 
    [United Kingdom] => Array ( [23] => 20 ) 
    [United States] => Array ( [26] => 19 [35] => 12 [40] => 10 [43] => 8 [47] => 7 [48] => 7 [49] => 7 [53] => 6 [54] => 6 [55] => 6 [56] => 6 [63] => 5 [76] => 4 [77] => 4 [90] => 3 [91] => 3 [92] => 3 [93] => 3 [94] => 3 ) 
    [Ecuador] => Array ( [34] => 12 [44] => 7 [83] => 3 ) 
    [Australia] => Array ( [41] => 9 [57] => 5 [97] => 2 ) 
    [Peru] => Array ( [52] => 6 ) 
    [China] => Array ( [58] => 5 ) 
    [El Salvador] => Array ( [59] => 5 ) 
    [Germany] => Array ( [60] => 5 [69] => 4 [85] => 3 [86] => 3 ) 
    [Paraguay] => Array ( [61] => 5 ) 
    [Poland] => Array ( [62] => 5 ) 
    [Armenia] => Array ( [65] => 4 ) 
    [Bolivia] => Array ( [66] => 4 [80] => 3 [81] => 3 [82] => 3 ) 
    [Canada] => Array ( [67] => 4 ) 
    [France] => Array ( [68] => 4 ) 
    [Guatemala] => Array ( [70] => 4 ) 
    [Nicaragua] => Array ( [74] => 4 ) 
    [Spain] => Array ( [75] => 4 [89] => 3 ) 
    [Uruguay] => Array ( [78] => 4 ) 
    [Argentina] => Array ( [79] => 3 ) 
    [Egypt] => Array ( [84] => 3 ) 
    [Italy] => Array ( [87] => 3 ) 
    [Nepal] => Array ( [88] => 3 ) 
    [Algeria] => Array ( [96] => 2 ) 
    [Belarus] => Array ( [98] => 2 ) 
    [Bulgaria] => Array ( [99] => 2 ) 
) 

我正在寻找与此类似的结果:

以色列:3400 巴勒斯坦:48 委内瑞拉:36

我尝试使用,但它不适合,我不知道如何转换它

ETC...

4

2 回答 2

2

使用array_sum()

$output = array();
foreach ($array as $k => $a) {
  $output[$k] = array_sum($a);
}
于 2013-05-26T09:05:29.743 回答
1

怎么样 :

foreach ($myArray as $k=>$subArray) {   
    $sumArray[$k] = 0;   
    foreach ($subArray as $id=>$value) {
       $sumArray[$k]+=$value;   
    }
}

由于 $k 代表您的国家/地区,因此您将其子数组的所有值相加并将其存储在一个映射中,该映射具有一个名称存储在 $k 中的键。

于 2013-05-26T08:38:18.197 回答