我正在尝试使用这些数组执行array_merge
,但我需要能够计算数组中特定值出现的次数并将数据反馈给我。
以下是原始数组
Array
(
[0] => this
[1] => that
)
Array
(
[0] => this
[1] => that
[2] => some
)
Array
(
[0] => some
[1] => hello
)
最终我希望它看起来像这样
Array
(
[this] => 2
[that] => 2
[some] => 2
[hello] = > 1
)
这最终会让我获得我需要的关键和价值。我在这个过程中尝试了'array_unique`,但意识到我可能无法计算它们出现的每个数组的实例,因为除了一个之外,它只是简单地删除它们。
我尝试了一些列表
$newArray = array_count_values($mergedArray);
foreach ($newArray as $key => $value) {
echo "$key - <strong>$value</strong> <br />";
}
但是我得到了这样的结果
Array
(
[this] => 2
[that] => 2
[some] => 2
[hello] = > 1
[this] => 3
[that] => 3
[some] => 3
[hello] = > 2
[this] => 2
[that] => 2
[some] => 2
[hello] = > 1
)
答案 0 :(得分:7)
使用array_count_values()
:
$a1 = array(0 => 'this', 1 => 'that');
$a2 = array(0 => 'this', 1 => 'that', 2 => 'some');
$a3 = array(0 => 'some', 1 => 'hello');
// Merge arrays
$test = array_merge($a1,$a2,$a3);
// Run native function
$check = array_count_values($test);
echo '<pre>';
print_r($check);
echo '</pre>';
给你:
Array
(
[this] => 2
[that] => 2
[some] => 2
[hello] => 1
)
编辑:正如 AlpineCoder 所述:
&#34;这仅适用于使用数字(或唯一)键的输入数组(因为array_merge将覆盖相同非整数键的值)。&#34;
答案 1 :(得分:1)
$res = array();
foreach ($arrays as $array) {
foreach ($array as $val) {
if (isset($res[$val])) {
$res[$val]++;
} else {
$res[$val] = 1;
}
}
}
答案 2 :(得分:0)
如提到的tyteen4a03,请使用嵌套的foreach
循环:
$arr1 = array('foo', 'bar');
$arr2 = array('foo', 'bar', 'baz');
$arr3 = array('baz', 'bus');
$result = array();
foreach(array($arr1, $arr2, $arr3) as $arr) {
foreach ($arr as $value) {
if (!isset($result[$value])) {
$result[$value] = 0;
}
++$result[$value];
}
}
print_r($result);
外部foreach
遍历每组项目(即每个数组),内部foreach
循环遍历每组中的每个项目。如果该项目尚未在$result
数组中,请在那里创建密钥。
结果:
Array
(
[foo] => 2
[bar] => 2
[baz] => 2
[bus] => 1
)