保持只有值存在于两个Array PHP中

时间:2012-07-26 19:05:44

标签: php arrays

我有两个数组,让我们说

$array1 = array(0 => 10, 1 => 21, 2 => 34, 'somekey' => 45, 'otherkey' => 15);
$array2 = array(0 => 9, 1 => 10, 2 => 14, 'otherkey' => 15, 'somekey' => 43);

我需要返回一个只包含两个数组所包含的值的数组,而不管它们的键。在这种情况下,结果数组在键0处包含值10,在键1处包含值15

2 个答案:

答案 0 :(得分:6)

使用array_intersect()

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

如果您想摆脱密钥,请通过array_values()运行该数组:

$array3 = array_values( $array3);

will set $array3来:

Array
(
    [0] => 10
    [1] => 15
)

答案 1 :(得分:1)

    <?php

    $array1 = array(0 => 10, 1 => 21, 2 => 34, 'somekey' => 45, 'otherkey' => 15);
    $array2 = array(0 => 9, 1 => 10, 2 => 14, 'otherkey' => 15, 'somekey' => 43);

    $array1 = array_values($array1);
    $array2 = array_values($array2);
    $array3 = array_merge($array1,$array2);

    echo '<pre>';
    print_r($array3);
    echo '</pre>';

?>