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

后端 未结 2 1415
难免孤独
难免孤独 2020-12-12 01:14

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

相关标签:
2条回答
  • 2020-12-12 01:44

    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.

    0 讨论(0)
  • 2020-12-12 01:46

    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";
    ?>
    
    0 讨论(0)
提交回复
热议问题