你好试着找到数组中的重复值我有这样的数组
2
所以我想在%
之后找到重复的foreach($array as $value){
$s = explode('%',$value);
if($s[1] == $s[1]){
echo 'there are duplicated 2';
}
}
所以我在foreach中使用了爆炸
$s[1]
所以我希望%
检查数组中const key1 = 'hello';
const key2 = 'world';
type _MyInterface = Record<typeof key1, {}> & Record<typeof key2, string>;
interface MyInterface extends _MyInterface { }
var _myObject = {} as MyInterface;
_myObject[key1] = { something: 'something' };
_myObject[key2] = 'some other things';
const myObject = _myObject;
之后的值是否重复
无论如何都要这样做
答案 0 :(得分:1)
您需要在循环浏览时收集右侧值并检查重复项。我通过“偏移”[2]
访问字符串的右侧值。找到后,您可以使用break
退出循环。
代码:(Demo)
$array=['1%2','3%4','1%2','1%3'];
$kept=[];
foreach($array as $i=>$v){
if(in_array($v[2],$kept)){
echo "Element (index $i) containing $v has duplicate right side value.";
break;
}
$kept[]=$v[2];
}
输出:
Element (index 2) containing 1%2 has duplicate right side value.
如果您要搜索以%2
结尾的所有元素,可以使用preg_grep()
。
代码:
$search=2;
$array=['1%2','1%3','1%4','3%2','5%2'];
var_export(preg_grep("/%{$search}$/",$array));
输出:
array (
0 => '1%2',
3 => '3%2',
4 => '5%2',
)
或者没有正则表达式,它将需要更多函数调用:
$search=2;
$array=['21%2','1%3','2%22','1%4','3%21','5%2'];
var_export(array_filter($array,function($v)use($search){return strpos($v,"%$search")+2===strlen($v);}));
输出:
array (
0 => '21%2',
5 => '5%2',
)
... [深呼吸]尝试回答#4 ......
代码:
$array=['1%2','1%3','1%4','3%2','5%2'];
foreach($array as $v){
$grouped[explode('%',$v)[1]][]=$v; // use right side number as key
}
var_export($grouped);
输出:
array (
2 =>
array (
0 => '1%2',
1 => '3%2',
2 => '5%2',
),
3 =>
array (
0 => '1%3',
),
4 =>
array (
0 => '1%4',
),
)
如果要计算数组中的右侧值:
$array=['1%2','1%3','1%4','3%2','5%2'];
$array=preg_replace('/\d+%/','',$array); // strip the left-size and % from elements
var_export(array_count_values($array)); // count occurrences
输出:
// [right side values] => [counts]
array (
2 => 3,
3 => 1,
4 => 1,
)