php - 匹配数组中的元素

时间:2010-12-16 04:15:58

标签: php arrays merge

我整天都在玩这个,并没有找到一个很好的方法来做到这一点......

我有两个数组,我正在尝试根据匹配值创建一个数组。

//$original

    Array
    (
        [0] => Array
            (
                [items] => Array
                    (
                        [0] => Array
                            (
                                [0] => PA
                                [1] => DZ
                                [2] => ER
                                [3] => TY
                            )

                        [1] => Array
                            (
                                [0] => KV
                                [1] => EN
                                [2] => CR
                            )

                        [2] => Array
                            (
                                [0] => HU
                                [1] => GO
                                [2] => GA
                                [3] => FI
                            )
                    )
            )
    )


//$compare    
    Array
    (
        [0] => Array
            (
                [items] => Array
                    (
                        [0] => Array
                            (
                                [0] => PA
                                [1] => AN
                                [2] => ER
                            )

                        [1] => Array
                            (
                                [0] => KV
                            )

                        [2] => Array
                            (
                                [0] => HU
                                [1] => XV
                                [2] => ZL
                                [3] => FI
                            )
                    )
            )
    )

我正在努力制作

//$similar
    Array
    (
        [0] => Array
            (
                [items] => Array
                    (
                        [0] => Array
                            (
                                [0] => PA
                                [2] => ER
                            )

                        [1] => Array
                            (
                                [0] => KV
                            )

                        [2] => Array
                            (
                                [0] => HU
                                [3] => FI
                            )
                    )
            )
    )

1 个答案:

答案 0 :(得分:2)

使用array_intersect

$similar = $compare;
$similar[0]['items'] = array_intersect($compare[0]['items'], $original[0]['items']);

codepad example