Php 避免请求值在给定数组中多次出现所需的正则表达式
我已收到请求的数组。我想验证一下。例如,如果我有数组Php 避免请求值在给定数组中多次出现所需的正则表达式,php,regex,validation,Php,Regex,Validation,我已收到请求的数组。我想验证一下。例如,如果我有数组 $array = ['red', 'yellow', 'green', 'red']; $request = ['colour' => 'red']; 在上述情况下,它应该通过验证,因为请求值在给定数组中多次出现。因此,根据您的新规范和编辑的问题: <?php $array = ['red', 'yellow', 'green', 'red']; $request = ['colour' => 'red']; //
$array = ['red', 'yellow', 'green', 'red'];
$request = ['colour' => 'red'];
在上述情况下,它应该通过验证,因为请求值在给定数组中多次出现。因此,根据您的新规范和编辑的问题:
<?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";
}
}
如果我能正确理解你的问题,我想这就是你想要的 如果我误解了,这将给你一个数组中出现的次数
如果需要数组中每个项目的计数,可以使用数组计数值 这将返回一个带有红色键和值2的数组
var_dump(array_count_values($arr));
如果您只希望红色作为输出,则可以使用array_diff对所有为1的值进行排序
你不需要正则表达式,只需在数组中使用即可。我想通过验证错误检查此键是否在此数组中出现多次而不是一次。您好,很抱歉,我在问题选项卡中添加了我的注释。我到底想要什么。
$array = ['red','red','yellow','green'];
$arr = array_unique($array);
// $arr would now be ['red','yellow','green'];
var_dump(array_count_values($arr));
$array = ['red', 'yellow', 'green', 'red'];
$counts = array_count_values($array);
$oneOrMore = array_diff($counts, [1]);
var_dump($oneOrMore);
//array(1) {
// ["red"]=>int(2)
//}