如何从 PHP 中的两个不同数组中获取公共值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17648962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get common values from two different arrays in PHP
提问by Ricky
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 takes a minimum time of execution. Please help me, friends.
我试过了array_intersect()
。我想获得一种执行时间最短的方法。请帮助我,朋友。
回答by Expedito
Native PHP functions are faster than trying to build your own algorithm.
本机 PHP 函数比尝试构建自己的算法要快。
$result = array_intersect($array1, $array2);
回答by JunM
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 )
回答by gayan
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);
?>
回答by da-hype
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);