PHP - Count duplicate values within two dimensional array, then display only unique values with the count

末鹿安然 提交于 2019-11-28 14:10:27

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));

See demo


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);

See demo 2


Click here for sample use case that will work with either method.

I make this way:

<?php

$log = array (
  array('Red', 'Steel'),
  array('Red', 'Wood'),
  array('Blue', 'Wood')
);

$materials = array();
$colors = array();

foreach($log as $line) {
  $colors[$line[0]] = (!isset($colors[$line[0]])) ? 1 : $colors[$line[0]] + 1;
  $materials[$line[1]] = (!isset($materials[$line[1]])) ? 1 : $materials[$line[1]] + 1;
}

?>

<h2>Colors</h2>\n
<?php
foreach ($colors as $color => $amount)
  echo "{$color} => {$amount}<br>\n";
?>
<h2>Materials</h2>\n
<?php
foreach ($materials as $material => $amount)
  echo "{$material} => {$amount}<br>\n";
?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!