for example, I have a array:
$objects = ['car', 'cat', 'dog', 'Peter'];
and another:
$types = [
'man' => ['Peter', 'John','...'],
'animal' => ['pig', 'cat', 'dog', '...'],
'vehicle' => ['bus', 'car', '...']
];
and my goal is get an array like:
$result = [
'man' => ['Peter'],
'animal' => ['cat', 'dog'],
'vehicle' => ['car']
]
what is the most efficient way to search within an array, in my current work, I use two foreach loop to search but figured it's too slow, I have about thousands of elements in my array.
Use array_intersect:
foreach ($types as $key => $type) {
$result[$key] = array_intersect($type, $objects);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With