如何在PHP中从两个不同的数组中获取公共值

时间:2022-06-11 08:18:35

I have two arrays with some user id

我有两个带有一些用户id的数组。

$array1 = array("5","26","38","42");

$array2 = array("15","36","38","42");

What i need is, I need the common values from the array as follows

我需要的是,我需要来自数组的公共值,如下所示

$array3 = array(0=>"38", 1=>"42");

I have tried array_intersect(). I would like to get a method that's take minimum time of execution. Please help me friends.

我曾经尝试过array_intersect()。我想要一个方法,它需要最少的执行时间。请帮我的朋友。

4 个解决方案

#1


24  

Native PHP functions are faster than trying to build your own algorithm.

本地PHP函数比尝试构建自己的算法要快。

$result = array_intersect($array1, $array2);

#2


1  

Use this one, though this maybe a long method:

使用这个方法,虽然这个方法可能很长:

$array1 = array("5","26","38","42");

$array2 = array("15","36","38","42");

$final_array = array();

foreach($array1 as $key=>$val){
    if(in_array($val,$array2)){
        $final_array[] = $val;
    }
}

print_r($final_array);

Result: Array ( [0] => 38 [1] => 42 )

结果:数组([0]=> 38 [1]=> 42)

#3


1  

I think you don't need to use $key=>$value to your problem so check this answer:

我认为你不需要使用$key=>$value来解决你的问题,所以请检查以下答案:

<?php
$array1 = array("5", "26", "38", "42");
$array2 = array("15", "36", "38", "42");

foreach ($array1 as $value) {
    if (in_array($value, $array2)) {
        $array3[] = $value;
    }
}

print_r($array3);
?>

#4


0  

array_intersect() works just fine.

array_intersect()就可以了。

array array_intersect ( array $array1 , array $array2 [, array $ ... ] )

数组array_intersect(数组$array1,数组$array2[,数组$…])

$array1 = array("5","26","38","42");

$array2 = array("15","36","38","42");

echo array_intersect($array1, $array2);

http://fr2.php.net/array_intersect

http://fr2.php.net/array_intersect

#1


24  

Native PHP functions are faster than trying to build your own algorithm.

本地PHP函数比尝试构建自己的算法要快。

$result = array_intersect($array1, $array2);

#2


1  

Use this one, though this maybe a long method:

使用这个方法,虽然这个方法可能很长:

$array1 = array("5","26","38","42");

$array2 = array("15","36","38","42");

$final_array = array();

foreach($array1 as $key=>$val){
    if(in_array($val,$array2)){
        $final_array[] = $val;
    }
}

print_r($final_array);

Result: Array ( [0] => 38 [1] => 42 )

结果:数组([0]=> 38 [1]=> 42)

#3


1  

I think you don't need to use $key=>$value to your problem so check this answer:

我认为你不需要使用$key=>$value来解决你的问题,所以请检查以下答案:

<?php
$array1 = array("5", "26", "38", "42");
$array2 = array("15", "36", "38", "42");

foreach ($array1 as $value) {
    if (in_array($value, $array2)) {
        $array3[] = $value;
    }
}

print_r($array3);
?>

#4


0  

array_intersect() works just fine.

array_intersect()就可以了。

array array_intersect ( array $array1 , array $array2 [, array $ ... ] )

数组array_intersect(数组$array1,数组$array2[,数组$…])

$array1 = array("5","26","38","42");

$array2 = array("15","36","38","42");

echo array_intersect($array1, $array2);

http://fr2.php.net/array_intersect

http://fr2.php.net/array_intersect