PHP - 计算二维数组中的重复值,然后仅显示带有计数的唯一值 [英] PHP - Count duplicate values within two dimensional array, then display only unique values with the count
问题描述
我已经为此工作了几天......但仍然无法达到我想要的结果.对此有任何帮助将不胜感激...在此先感谢您.
我在 $log 中存储了一个多数组,当您打印_r($log) 时显示如下:
Array ( [0] => Array ( [0] => Red [1] => Steel )[1] =>阵列( [0] => 红色 [1] => 木头)[2] =>阵列( [0] => 蓝色 [1] => 木头))
目前我有这个:
$counts = $log;foreach ($log as $value) {foreach ($value as $k => $v) {if (!isset($counts[$k])) $counts[$k] = array();如果 (!isset($counts[$k][$v])) $counts[$k][$v] = 0;$counts[$k][$v] += 1;}}foreach ($counts as $k => $v1) {foreach ($v1 as $v => $count) {echo "$v => $count
";}}
显示:
0 =>红色的1 =>钢红色 =>2蓝色 =>10 =>红色的1 =>木头钢 =>1木材 =>20 =>蓝色1 =>木头
但我真的希望得到以下结果:
颜色
红色 =>2蓝色 =>1<h2>材料</h2>钢 =>1木材 =>2
如果你使用的是 PHP >= 5.5
,你可以使用 array_column(),结合 array_count_values():
$colors = array_count_values(array_column($log, 0));$materials = array_count_values(array_column($log, 1));
<小时>或者,如果您不使用 PHP >= 5.5
,这将适用于 PHP 4, 5
:
$colors = $materials = array();foreach ($log as $a){$colors[] = $a[0];$材料[] = $a[1];}$colors = array_count_values($colors);$materials = array_count_values($materials);
<小时>I've been working on this for a couple days now... and still haven't been able to achieve my desired results. Any help would on this would be greatly appreciated... thank you in advance.
I have a multi-array stored in $log, which displays like this when you print_r($log):
Array ( [0] => Array ( [0] => Red [1] => Steel )
[1] => Array ( [0] => Red [1] => Wood )
[2] => Array ( [0] => Blue [1] => Wood )
)
Currently I have this:
$counts = $log;
foreach ($log as $value) {
foreach ($value as $k => $v) {
if (!isset($counts[$k])) $counts[$k] = array();
if (!isset($counts[$k][$v])) $counts[$k][$v] = 0;
$counts[$k][$v] += 1;
}
}
foreach ($counts as $k => $v1) {
foreach ($v1 as $v => $count) {
echo "$v => $count <br />";
}
}
Which Displays:
0 => Red
1 => Steel
Red => 2
Blue => 1
0 => Red
1 => Wood
Steel => 1
Wood => 2
0 => Blue
1 => Wood
But I'm really looking to have an end result of:
<h2>Colors</h2>
Red => 2
Blue => 1
<h2>Materials</h2>
Steel => 1
Wood => 2
If you are using PHP >= 5.5
, you can use array_column(), in conjunction with array_count_values():
$colors = array_count_values(array_column($log, 0));
$materials = array_count_values(array_column($log, 1));
Or, if you're not using PHP >= 5.5
, this will work in PHP 4, 5
:
$colors = $materials = array();
foreach ($log as $a){
$colors[] = $a[0];
$materials[] = $a[1];
}
$colors = array_count_values($colors);
$materials = array_count_values($materials);
Click here for sample use case that will work with either method.
这篇关于PHP - 计算二维数组中的重复值,然后仅显示带有计数的唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!