我有来自请求的数组。我想验证一下。例如。如果我有数组,
$array = ['red', 'yellow', 'green', 'red'];
$request = ['colour' => 'red'];
在上述情况下,它应该通过验证,因为请求值在给定数组中多次出现。
答案 0 :(得分:1)
因此,根据您的新规格和已修改的问题:
<?php
$array = ['red', 'yellow', 'green', 'red'];
$request = ['colour' => 'red'];
// Error counter
$errors = 0;
// If request shows up in the array.. move to next block
if( in_array( $request['colour'], $array ) ){
/* Check how many times this key value shows up,then assign to count
variable.
In this example, $request['colour'] is red
array_count_values($arr) returns an array
$array['red'=> 2,'yellow'=> 1,...], so
show me the **count** in this array at array_key position for "red",
being two.
*/
$count = array_count_values( $array )[ $request['colour'] ];
// if this count is more than 1, increment our error flag for use later
if ($count > 1){
$errors++;
echo "Ut oh, this value shows up more than once in our array";
}
}
或为简单起见:
$count = array_count_values( $array )[ $request['colour'] ];
if ($count > 1){ $errors++; }
echo $errors;
答案 1 :(得分:0)
如果我正确理解您的问题,我想这就是您想要的http://php.net/manual/en/function.array-unique.php
$array = ['red','red','yellow','green'];
$arr = array_unique($array);
// $arr would now be ['red','yellow','green'];
如果我误解了,这将为您提供数组中出现的次数 http://us2.php.net/manual/en/function.array-count-values.php
答案 2 :(得分:0)
如果要计数数组中每个项目的计数,可以使用array_count_values。
这将返回带有键“ red”和值2的数组。
var_dump(array_count_values($arr));
如果只希望“ red”作为输出,则可以使用array_diff来排序所有1
的值。
$array = ['red', 'yellow', 'green', 'red'];
$counts = array_count_values($array);
$oneOrMore = array_diff($counts, [1]);
var_dump($oneOrMore);
//array(1) {
// ["red"]=>int(2)
//}