2017-04-05 36 views
2

我有这些数组:如何知道对关键的,从返回array_intersec

$a = ['a','b','c','d','e','f']; 
$b = ['d','e','f']; 

如果我使用array_intersect上面像阵列,

$c = array_intersect($a, $b); 
$d = array_intersect($b,$a); 

$ C将返回:

Array 
(
    [3] => d 
    [4] => e 
    [5] => f 
) 

and $ d will return:

Array 
(
    [0] => d 
    [1] => e 
    [2] => f 
) 

我怎样才能知道该对那些array_intersection等的关键的,

[3] --> [0] 
[4] --> [1] 
[5] --> [2] 

我的意思,[3]数组$a的[0]在阵列$b相交具有索引的索引。我怎么知道?

非常感谢。

+0

选择的答案是时间,因为耗时' array_search()': - https://eval.in/768069(检查时间)对我的答案链接(https://eval.in/768032)。实际上并不需要。如果阵列长度增加,将变得更加方便。 –

+0

'foreach()'和'array_search()'?不是一个好的方法(谈论由OP选择的答案)。更费时: - https://eval.in/768069(检查时间)对我的答案链接(https://eval.in/768032)。不需要这样做。如果数组长度增加 –

回答

1
<?php 
$a = ['a', 'b', 'c', 'd', 'e', 'f']; 
$b = ['d', 'e', 'm', 'f']; 
$intersect = array_intersect($a, $b); 
$key_intersect = []; 
foreach ($intersect as $key => $value) { 
    $key_intersect[$key] = array_search($value, $b); 
} 
var_dump($key_intersect); 

array $b我已经插入一个额外的元素,以检查是否它完美的作品即使有留下了一些元素。

+1

因为'array_search()'而耗时会更方便: - https://eval.in/768069(检查时间)。实际上并不需要。如果阵列长度增加,将变得更加方便。 –

3

你想是这样的: -

<?php 

$a = ['a','b','c','d','e','f']; 
$b = ['d','e','f']; 
$c= array_intersect($a,$b); 
$d= array_intersect($b,$a); 
$intersection_keys_array = array_combine (array_keys($c),array_keys($d)); // combine $c and $d so that $c values become key and $d values become values in resultant array 
print_r($intersection_keys_array); 

输出: - https://eval.in/768032

或者

多一点花哨的输出: - https://eval.in/768033

相关问题