计算php中数组中某项的使用次数


Count how many times an item from an array is used in php

我想写一个代码,可以使用一点帮助。假设我有一个5种颜色的测试文件。我只希望每种颜色使用10次。

EDIT:编辑代码以更多地反映我的设置。主要需要做一个函数,我可以调用返回我的5种颜色中没有使用超过10次的1种。

$colors = array_map("trim", file("colorlist.txt")); //loads all my colors
// echos all my colors
foreach($colors as $color){
  echo ''.$color;
}
function checklimit($string){
BS CODING......
$currentcolor = getcolor();
}

function getcolor() {
 $totalpercolor = 10;
  If all $colors $totalused = $totalpercolor {
      exit;
  } else {
  shuffle($colors)
  Return a single color who's $totalused < $totalpercolor;
  $color's $totalused = $totalused++
  }
}

$result = mysql_query("SELECT whatever FROM $table_name WHERE doesntmatter IS NULL");
while ($row = mysql_fetch_assoc($results)){
  $data = checklimit($string);
}

Org:

$colors = array(file("colorlist.txt"));
$i = 1;
foreach($colors as $color){
  if color[i] <= 10 {
  var color[i] = 0++;
  i++;
  } else {
     If all colors = 10 { 
         end;
     } else {
           start loop over, get new color
     }
  }
}

我肯定这样做不对。所以任何帮助都会很好。

foreach($colors as $color){
    if($color_num[$color])
     $color_num[$color]++;
    else $color_num[$color] = 1;
 }

在循环结束时,您有一个$color_num数组,其中包含每种颜色的计数。现在您可以添加一些循环内检查,例如:if($color_num[$color] >= 10) ...

——但你确实应该发布有效的代码,所以我们可以提供建设性的答案。

加载颜色

$colors = array_map("trim", file("log.txt"));
printf("%s'n", implode(",", $colors)); //red,blue,orage,black,purble

要重复使用颜色,您可以使用modulus

$total = count($colors);
$limit = 10;
for($i = 0; $i < $limit; $i ++) {
    echo $colors[$i % $total], PHP_EOL;
}

或Infinite Iterator

$limit = 10;
$iterator = new InfiniteIterator(new ArrayIterator($colors));
foreach(new LimitIterator($iterator, 0, $limit) as $color) {
    echo $color, PHP_EOL;
}

都返回

red
blue
orage
black
purble
red
blue
orage
black
purble

我不知道你想要什么,所以我只回答你可能想要的三种情况:如果你需要打印每种颜色10次,然后继续下一个颜色

$colors = array_map("trim", file('colorlist.txt'));
foreach ($colors as $color)
{
    for ($i=1; $i<=10; $i++)
        print $color . PHP_EOL;
}

将输出:

blue
blue
blue
blue
blue
blue
blue
blue
blue
blue
green
green
green
green
green
green
green
green
green
green
(the other 3 colors)

如果您需要按顺序输出颜色:

$colors = array_map("trim", file('colorlist.txt'));
for ($i=1; $i<=10; $i++)
{
    foreach($colors as $color)
        print $color . PHP_EOL;
}

将输出你:

blue
green
red
pink
gray
blue
green
red
pink
gray

如果你需要随机输出颜色,并且每种颜色必须出现10次:

$colors_file = array_map("trim", file('colorlist.txt'));
foreach ($colors_file as $color)
    $colors[] = array($color, 0);
while(!empty($colors))
{
    $index = rand(0,count($colors)-1);
    echo $colors[$index][0] . PHP_EOL;
    if (++$colors[$index][1] == 19)
    {
        unset($colors[$index]);
        $colors = array_values($colors);
    }
}

将输出:

pink
red
red
blue
gray
blue
green
blue
gray
gray
green
red
red