Foreach循环在数组中,获取出现值

时间:2018-02-05 08:59:59

标签: php arrays

我在数组中有简单的foreach循环

key_info

我想获取值的出现次数,例如<?php $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value <br>"; } ?> ,因此文本将为:

红色是0出现

绿色是1出现

...

我该怎么做?

5 个答案:

答案 0 :(得分:1)

使用此

<?php  
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $key=>$value) {
  echo $value . " is " . $key . " occurence <br>";
}
?>

答案 1 :(得分:1)

使用foreach时,您可以获得密钥和值。这里,由于您尚未指定键,因此键将是数组元素的索引值。为了解决问题,您需要使用foreach($colors as $index => $value)

<?php  
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $index => $value) {
  echo "$value is $index occurence <br>";
} 

答案 2 :(得分:1)

没有必要使用奇特的功能来实现这一目标。只需用for循环替换foreach循环,这样就可以使用现成的索引器:

<?php

    $colors = array("red", "green", "blue", "yellow");

    for ($i = 0; $i < count($colors); ++$i) {
        echo $colors[$i]." is ".$i." occurrence<br>";
    }

?>

或者,但仅因为您的数组未定义键,您可以使用以下方法:

<?php

    $colors = array("red", "green", "blue", "yellow");

    foreach ($colors as $index=>$value) {
        echo "$value is $index occurrence<br>";
    }

?>

答案 3 :(得分:0)

使用array_count_values功能获得所需的结果。

$colors = array("red", "green", "blue", "yellow");
$counts = array_count_values($colors);

foreach ($counts as $key=>$value) {
  echo $key."=>".$value."<br>"; 
}

请参阅此处的文档http://php.net/manual/en/function.array-count-values.php

答案 4 :(得分:0)

按照我在评论部分中的建议尝试此操作:

<?php  
$colors = array("red", "green", "blue", "yellow");
$occurences = array_count_values($colors);

foreach ($colors as $value) {
   echo "$value is $occurences[$value] <br>";
}
?>