Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php array match within a two dimensional array

Tags:

arrays

php

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.

like image 859
Jin Aazoe Avatar asked Jun 14 '26 00:06

Jin Aazoe


1 Answers

Use array_intersect:

foreach ($types as $key => $type) {
  $result[$key] = array_intersect($type, $objects);
}
like image 106
Ruslan Osmanov Avatar answered Jun 16 '26 20:06

Ruslan Osmanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!