php数组在二维数组中匹配

时间:2017-01-16 05:02:21

标签: php arrays

例如,我有一个数组:

$objects = ['car', 'cat', 'dog', 'Peter'];

和另一个:

$types = [
    'man' => ['Peter', 'John','...'],
    'animal' => ['pig', 'cat', 'dog', '...'],
    'vehicle' => ['bus', 'car', '...']
];

我的目标是得到一个像:

这样的数组
$result = [
    'man' => ['Peter'],
    'animal' => ['cat', 'dog'],
    'vehicle' => ['car']
]

在数组中搜索最有效的方法是什么,在我目前的工作中,我使用两个foreach循环进行搜索,但认为它太慢了,我的数组中有数千个元素。

2 个答案:

答案 0 :(得分:7)

使用array_intersect

foreach ($types as $key => $type) {
  $result[$key] = array_intersect($type, $objects);
}

答案 1 :(得分:0)

$objects = ['car', 'cat', 'dog', 'Peter'];

$types = [
    'man' => ['Peter', 'John'],
    'animal' => ['pig', 'cat', 'dog'],
    'vehicle' => ['bus', 'car']
];

foreach ($types as $key => $type) {
  $result[$key] = array_intersect($type, $objects);
}

echo '<pre>';
print_r($result);





Array
(
    [man] => Array
        (
            [0] => Peter
        )

    [animal] => Array
        (
            [1] => cat
            [2] => dog
        )

    [vehicle] => Array
        (
            [1] => car
        )

)