当前位置:网站首页>PHP takes the difference set of two arrays

PHP takes the difference set of two arrays

2022-06-25 12:29:00 Chafferer WANG

Replace with the following method array_diff()

/**  Application scenarios :  for example :  Two existing arrays $arr1, $arr2 $arr1 = ['a', 'a', 'b']; $arr2 = ['a', 'b', 'b'];  If we want to take at this time arr1 But not in arr2 When data in ,  Use array_diff($arr1, $arr2) The output result is [];  Use array_diff_repeat($arr1, $arr2) The output is ['temp_arr1' => 'a', 'temp_arr2' => 'b']; *  The ginseng :$arr1,$arr2 */
public function array_diff_repeat($arr1, $arr2) {
    
	$temp_arr1 = [];//  stay $arr1 But not in $arr2 Data in 
    $temp_arr2 = [];//  stay $arr2 But not in $arr1 Data in 
    foreach ($arr1 as $arr1_key => $arr1_id) {
    
        $index_id = array_search($arr1_id, $arr2, true);
        if($index_id !== false) {
    
            unset($arr1[$arr1_key]);
            unset($arr2[$index_id]);
        } else {
    
            array_push($temp_arr1, $arr1_id);
        }
    }
    foreach ($arr2 as $arr2_key => $arr2_id) {
    
        $index_id = array_search($arr2_id, $arr1, true);
        if($index_id !== false) {
    
            unset($arr1[$arr2_key]);
            unset($arr2[$index_id]);
        } else {
    
            array_push($temp_arr2, $arr2_id);
        }
    }
	return ['temp_arr1' => $temp_arr1, 'temp_arr2' => $temp_arr2];
}
原网站

版权声明
本文为[Chafferer WANG]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200531230885.html

随机推荐