我在多维数组中计算值时寻求一些帮助。
我有一个数组键,就像" barrack obama" - 值将是一长串数字。
然后下一个数组键可能是"另一个名称"这些值也是一长串的数字。
最多约10个数组键同样排列。
示例var_dump:
array(10) { ["barack obama"]=> array(4260) { [0]=> string(2) "19" [1]=> string(2) "92" [2]=> string(2) "27" [3]=> string(2) "55" [4]=> string(2) "56" [5]=> string(2) "57" [6]=> string(4) "1409" [7]=> string(4) "1384" [8]=> string(4) "1362" [9]=> string(4) "1345" [10]=> string(4) "1280" }
["united states"]=> array(5886) { [0]=> string(2) "72" [1]=> string(2) "81" [2]=> string(2) "89" [3]=> string(2) "90" [4]=> string(2) "92" [5]=> string(2) "21" [6]=> string(2) "23" [7]=> string(2) "27" [8]=> string(2) "32" [9]=> string(2) "47" [10]=> string(2) "55" }
如何计算数组键(名称)中唯一值(数字)的出现次数。
所以,如果55岁的话,那就是" barack obama"和#34;美国"它会得2分。
理想情况下,我只想保留一个或多个键中出现的值,但在我至少得分后,我可以处理。
答案 0 :(得分:1)
创建结果数组。然后迭代外部数组,并在循环内部迭代子数组并相应地递增结果数组:
$data = array(
"barack obama" => array(0,50,150,250,600,900,45,150,1050),
"tom jones" => array(80,120,150,75,250,80,1100,1900),
"bob mugabe" => array(50,120,10,0,250,900,600,45,1000,1010),
);
$results = array(); // create an empty array to store our results
foreach ( $data as $item ): // loop the outer array
foreach ( $item as $key => $value ): // loop the inner array
if ( array_key_exists($value,$results) ){ // check if value is already in results, if not set to 1, otherwise increment
$results[$value] = $results[$value] + 1;
} else {
$results[$value] = 1;
}
endforeach;
endforeach;
// show our results array
print "<pre>";
print_r($results);
答案 1 :(得分:0)
迭代这样的多维数组:
<?php
$data = array(
'barack_obama' => array('19', '92', '27', '55', '57', '1409', '1384', '1362', '1345', '1280'),
'united_states' => array('72', '81', '89', '90', '92', '21', '23', '27', '32', '47', '55'),
);
$aggregator = [];
foreach (array_keys($data) as $i) {
for ($j = 0, $entryCount = count($data[$i]); $j < $entryCount; $j++) {
$index = $data[$i][$j];
$aggregator[$index] = isset($aggregator[$index]) ? $aggregator[$index] + 1 : 1;
}
}
var_export($aggregator);
结果:
array ( 19 => 1, 92 => 2, 27 => 2, 55 => 2, 57 => 1, 1409 => 1, 1384 => 1, 1362 => 1, 1345 => 1, 1280 => 1, 72 => 1, 81 => 1, 89 => 1, 90 => 1, 21 => 1, 23 => 1, 32 => 1, 47 => 1, )