如何在保持数量的同时从数组中删除重复值?

时间:2012-05-18 19:19:46

标签: php arrays loops

我们有一个数组填充了类别名称(其中许多重复),我们需要构建一个二维数组,消除数组一侧的重复,并在数组的另一侧有总数如何很多时候,类别名称出现在原始数组中。以下是两张图片,以便您更好地了解我所描述的内容:http://postimage.org/image/ptms64cl9/http://postimage.org/image/70x6qt0l9/。现在,我确信有不止一种方法可以做到这一点,但我想了解这本书的方式。以下是代码,请注意$ mismatch_categories包含重复类别的原始数组:

 $category_totals = array(array($mismatch_categories[0], 0));
    foreach ($mismatch_categories as $category) {
      if ($category_totals[count($category_totals) - 1][0] != $category) {
        array_push($category_totals, array($category, 1));
      }
      else {
        $category_totals[count($category_totals) - 1][1]++;
      }
    }

我不了解这个例子的一个主要问题是数组中的数组。这里实际上没有3个阵列:

 $category_totals = array(array($mismatch_categories[0], 0));

如果有3个数组,我该如何使用它们的索引?这样的事可能吗?:

 $category_totals[0][0][0];

3 个答案:

答案 0 :(得分:1)

希望它能帮助你理解。

<?php
     echo '<pre>';
     $mismatch_categories = array('cat', 'cat', 'cow', 'book', 'box', 'box', 'box');
     echo 'Input Mismatch Category::<br />';
     print_r($mismatch_categories);
     echo '<br />';
     $category_totals = array(array($mismatch_categories[0], 0));
     echo 'categroy totals that holds final data' . '<br />';
     $counter = 0;
     print_r($category_totals);
     foreach ($mismatch_categories as $category) {
         echo 'Iteration ' . $counter++ . '<br /><br />';
         echo 'Current category value::' . $category . "<br /><br />";
         echo 'Value of category_totals[' . count($category_totals) . '- 1][0] :: ' .         $category_totals[count($category_totals) - 1][0] . '<br/><br />';
         echo 'Are they equal' . '<br />';
         if ($category_totals[count($category_totals) - 1][0] != $category) {
              echo 'Not matched so pushed into array with occurence of one<br />';
              array_push($category_totals, array($category, 1));
         } else {
              echo 'matches so count is increased by 1' . "<br />";
              $category_totals[count($category_totals) - 1][1]++;
         }
         echo 'category totals:' . '<br />';
         print_r($category_totals);
   }
   echo 'Final value of category_totals::';
   print_r($category_totals);
?>

答案 1 :(得分:1)

检查array_count_values()函数(http://www.php.net/manual/pl/function.array-count-values.php)应该做的诀窍

源数组:

array(
    0 => 'Cat 1',
    1 => 'Cat 1',
    2 => 'Cat 1',
    3 => 'Cat 2',
    4 => 'Cat 2',
    5 => 'Cat 3',
    6 => 'Cat 4',
)

结果array_count_values():

array(
    'Cat 1' => 3,
    'Cat 2' => 2,
    'Cat 3' => 1,
    'Cat 4' => 1,
)

答案 2 :(得分:0)

跟进评论中的建议:

<?php
$mismatch_categories = array('cat', 'cat', 'cow', 'book', 'box', 'box', 'box');

$cat_counts = array_count_values($mismatch_categories);
// = array('cat' => 2, 'cow' => 1, 'book' => 1, 'box' => 3)

$categories = array_unique($mismatch_categories);
// = array('cat', 'cow', 'book', 'box');
?>

换句话说,正是你要找的东西。

在这里编写自己的处理循环的唯一原因是编码实践。