>我有一个数组,我将类型填充为每个元素的字符串。例如:
类型数组
type1 | type2 | type2 | type3 | type2 | type1 | type3
$types = array('type1', 'type2', 'type2', 'type3', 'type2', 'type1', 'type3')
现在,我想在迭代数组时计算每种类型的出现次数。
例如:
当我在数组的第一个元素时,我想返回:
type1 : 1
type2 : 0
type3 : 0
当我在第四个元素时,我想要:
type1 : 1
type2 : 2
type3 : 1
实际上,我只对查找我正在寻找的元素类型的出现感兴趣。例如:fourth element
type3: 1
有没有 php 函数来做到这一点?或者我将不得不迭代整个数组并计算类型的出现次数?
谢谢
没有本机函数来执行此操作。但是我们可以写一个简单的:
$items = array(
'type1',
'type2',
'type2',
'type3',
'type2',
'type1',
'type3'
);
foreach ($items as $order => $item) {
$previous = array_slice($items, 0, $order + 1, true);
$counts = array_count_values($previous);
echo $item . ' - ' . $counts[$item] . '<br>';
}
此代码生成以下内容:
type1 - 1
type2 - 1
type2 - 2
type3 - 1
type2 - 3
type1 - 2
type3 - 2
我不确定我是否完全理解了你的问题,但是如果你想计算数组的所有值,你可以使用array_count_values
函数:
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
The above example will output:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
这是正确的解决方案:
$index = 4;
$array = array('type1', 'type2', 'type2', 'type3', 'type2', 'type1', 'type3')
var_dump( array_count_values( array_slice( $array, 0, $index)));
如果使用array_slice
获取数组的一部分,然后运行它以array_count_values
,则实际上可以计算子数组的值。因此,对于任何$index
,您都可以计算从 0
到 $index
的值。
这输出:
array(3) { ["type1"]=> int(1) ["type2"]=> int(2) ["type3"]=> int(1) }