计算合并数组中值/键的实例并按计数设置值

Ces*_*ich 0 php arrays

我正在尝试array_merge使用这些数组,但我需要能够计算数组中特定值出现的次数并将数据返回给我.

这是原始数组

Array
(
    [0] => this
    [1] => that
)
Array
(
    [0] => this
    [1] => that
    [2] => some
)
Array
(
    [0] => some
    [1] => hello
)
Run Code Online (Sandbox Code Playgroud)

最终我希望它看起来像这样

Array
(
    [this] => 2
    [that] => 2
    [some] => 2
    [hello] = > 1
)
Run Code Online (Sandbox Code Playgroud)

这最终将使我获得我需要的关键和价值.我在这个过程中尝试了'array_unique`,但意识到我可能无法计算它们出现的每个数组的实例,因为除了一个之外,它只是简单地删除它们.

我尝试了一些清单

$newArray = array_count_values($mergedArray);

foreach ($newArray as $key => $value) {
    echo "$key - <strong>$value</strong> <br />"; 
}
Run Code Online (Sandbox Code Playgroud)

但我得到的结果是这样的

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
)
Run Code Online (Sandbox Code Playgroud)

Ras*_*att 8

用途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>';
Run Code Online (Sandbox Code Playgroud)

给你:

Array
(
    [this] => 2
    [that] => 2
    [some] => 2
    [hello] => 1
)
Run Code Online (Sandbox Code Playgroud)

编辑:正如AlpineCoder所说:


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