您的位置:首页 > 其它

列出两个数组中相同的字符(字符串组成数组)(数组的交集、差集)

2017-07-29 14:22 686 查看
一:求两个数组中相同元素
//字符串组成数组
$a1="11,12,13,11,12,13,15";
$a11 = explode(',', $a1);
$a2="10,12,13,15";
$a22=explode(',', $a2);;

//$a11 = array("Apple","Banana","Orange","Apple");
//$a22 = array("Pear","Apple","Grape");
$intersection = array_intersect($a22, $a11); //个数少的数组排在前面
$intersection2 = array_intersect($a11, $a22);
print_r($intersection);  //输出:Array ( [1] => 12 [2] => 13 [3] => 15 )
print_r($intersection2); //输出:Array ( [1] => 12 [2] => 13 [4] => 12 [5] => 13 [6] => 15 )


个数少的数组放在前面,就可以保证只取得相同的字条

二,求一个数组修改后新增加元素的数组

修改后这个数组可能会新增加一些新的元素,也可能只是减少一些元素,但是没有新增元素

//字符串组成数组
$a1="11,12,13";
$a11 = explode(',', $a1);
$a2="10,12,15,16";//数组个数会增多,或者会减少
$a22=explode(',', $a2);;

$intersection3 = array_diff($a22, $a11); //少的数组必需在前面 才能新增加的

print_r($intersection3);


查询字符串在数组中出现的次数

<?php

$array = array(1, "hello", 1, "world", "hello","11");
//计算$string在$array(需为数组)中重复出现的次数
function get_array_repeats(array $array,$string) {

$count = array_count_values($array);
//统计中重复元素的次数,再重组数组,
//打印array_count_values($array)出,结果:
//Array(
//    [1] => 2
//    [hello] => 2
//    [world] => 1
//)
if (key_exists($string,$count)){
return $count[$string];
}else{
return 0;
}
}
$string="11";
echo get_array_repeats($array,$string);

?>


查询字符在字符串中出现的次数

<?php
$colors= array('red','blue','green','yellow','red');
$str = implode(',',$colors);
$count=substr_count($str,'red');
echo $count;
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: