对合并数组中值/键的实例进行计数,并按计数设置值


Count instances of value/key in merged arrays and set value by count

我正在考虑尝试对这些数组进行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
)

使用 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所指出的:


"这仅适用于使用数字(或唯一(键的输入数组(因为array_merge将覆盖同一非整数键的值(。

$res = array();
foreach ($arrays as $array) {
    foreach ($array as $val) {
        if (isset($res[$val])) {
            $res[$val]++;
        } else {
            $res[$val] = 1;
        }
    }
}

正如 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
)