3 回答
TA贡献1795条经验 获得超7个赞
有一个原生 PHP 函数可以实现此目的。
只需将一个值推入普通数组即可添加它:
$values = [];
$values[] = 'hello';
$values[] = 'bye';
$values[] = 'hello';
$values[] = 'John';
$values[] = 'hello';
$values[] = 'bye';
// Count the unique instances in the array
$totals = array_count_values($values);
// If you want to sort them
asort($totals);
// If you want to sort them reversed
arsort($totals);
结果$totals数组将是:
Array
(
[hello] => 3
[bye] => 2
[John] => 1
)
TA贡献1786条经验 获得超11个赞
将其构建到一个类中将允许您根据需要创建计数器。它有一个私有变量,用于存储每次调用的计数inc()(因为它是增量而不是add())。
该ordered()方法首先对计数器进行排序(用于arsort保持键对齐)...
class Counter {
private $counters = [];
public function inc ( string $name ) : void {
$this->counters[$name] = ($this->counters[$name] ?? 0) + 1;
}
public function ordered() : array {
arsort($this->counters);
return $this->counters;
}
}
所以
$counter = new Counter();
$counter->inc("first");
$counter->inc("a");
$counter->inc("2");
$counter->inc("a");
print_r($counter->ordered());
给...
Array
(
[a] => 2
[first] => 1
[2] => 1
)
TA贡献1851条经验 获得超3个赞
您可以通过以下方式执行此操作:
function count_array_values($my_array, $match)
{
$count = 0;
foreach ($my_array as $key => $value)
{
if ($value == $match)
{
$count++;
}
}
return $count;
}
$array = ["hello","bye","hello","John","bye","hello"];
$output =[];
foreach($array as $a){
$output[$a] = count_array_values($array, $a);
}
arsort($output);
print_r($output);
你会得到类似的输出
Array ( [hello] => 3 [bye] => 2 [John] => 1 )
- 3 回答
- 0 关注
- 112 浏览
添加回答
举报