PHP - Count duplicate values within two dimensiona

2019-01-20 16:29发布

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

2条回答
一纸荒年 Trace。
2楼-- · 2019-01-20 17:00

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";
?>
查看更多
Ridiculous、
3楼-- · 2019-01-20 17:23

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.

查看更多
登录 后发表回答