2017-04-05 38 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

相關問題