我用逗号分隔n个stings包含1,2,3,4,5,6
等数字,其长度可以是n
。我必须找到所有字符串中出现的数字。
示例输入:
$str1 = '1,2,3,4,5,6,7,8,9';
$str2 = '0,1,4,5,6,7,10,20,23,34,333,78';
$str3 = '5,4,8,3,1,1,1,5,6';
预期产出:
$result = '1,4,5,6';
我知道我可以通过比较每个字符串来做到这一点,但效率并不高。 第二个选项是获取最短的字符串,然后根据每个字符串检查该字符串的数字。它比前一个效率低。
我想要的是获得更有效的方法。
修改
我的html,我从中获取值:
<form name="cstm_data_form" id="cstm_data_form">
<div id="dataSet0" onclick="removeCandidate(0)">
<input type="hidden" name="hidden_ward_name[0]" value="1,2,3,4,5,6,7,8,9,10,11,12,12,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,50,52,53,54,58,59,60,61,62,63,64,65,66">
</div>
<div id="dataSet1" onclick="removeCandidate(1)">
<input type="hidden" name="hidden_ward_name[1]" value="4,5,6,7,8,9,10,11,12,13,14,15,16,64,65,66">
</div>
<div id="dataSet2" onclick="removeCandidate(2)">
<input type="hidden" name="hidden_ward_name[2]" value="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,53,54,55,56,57,58,59,60,61,62,63,64,65,66">
</div>
<div id="dataSet3" onclick="removeCandidate(3)">
<input type="hidden" name="hidden_ward_name[3]" value="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35">
</div>
</form>
答案 0 :(得分:2)
这应该适合你:
通过逗号循环浏览所有变量,explode()
并将展开的数组放入$arr
。
在此之后,只需使用array_intersect()
致电call_user_func_array()
,即可以这种方式调用该功能:array_intersect($arr[0], $arr[1], ...)
。
最后,只需使用array_unique()
从数组中获取所有唯一值。
<?php
$str1 = '1,2,3,4,5,6,7,8,9';
$str2 = '0,1,4,5,6,7,10,20,23,34,333,78';
$str3 = '5,4,8,3,1,1,1,5,6';
$i = 1;
while(isset(${"str" . $i})) {
$arr[] = explode(",", ${"str" . $i});
$i++;
}
$result = array_unique(call_user_func_array("array_intersect", $arr));
print_r($result); //As a string: echo implode(",", $result);
?>
输出:
Array
(
[0] => 1
[3] => 4
[4] => 5
[5] => 6
)
答案 1 :(得分:1)
尝试
$result = array_unique(array_intersect(explode(',', $str1), explode(',', $str2), explode(',', $str3)));
答案 2 :(得分:0)
$str1 = array("1","2",...);
$str2 = ...;
$str3 = ...;
$result = array_intersect($str1,$str2,$str3);
这应该有效。如果您希望,
像其他人一样向您展示explode()
。
答案 3 :(得分:0)
将您的字符串转换为数组,然后array_intersect
将返回常用值。
$arr1 = explode(',','1,2,3,4,5,6,7,8,9');
$arr2 = explode(',','0,1,4,5,6,7,10,20,23,34,333,78');
$arr3 = explode(',','5,4,8,3,1,1,1,5,6');
$arrayInterset = array_intersect($arr1, $arr2, $arr3);
echo '<pre>';print_r($arrayInterset);echo '</pre>';
输出
Array
(
[0] => 1
[3] => 4
[4] => 5
[5] => 6
)
答案 4 :(得分:0)
对于html表单上下文中的内容,作为循环遍历您的值:
foreach($_REQUEST['hidden_ward_name'] as $key=>$string) {
if($key == 0) {
$result = array_unique(explode(',', $string));
} else {
$result = array_intersect(array_unique(explode(',', $string)), $result);
}
}
print_r(array_sort($result));