3

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.

2 Answers 2

7

Use array_intersect:

foreach ($types as $key => $type) {
  $result[$key] = array_intersect($type, $objects);
}
Sign up to request clarification or add additional context in comments.

1 Comment

But I think add an array_values maybe more fit:array_values(array_intersect($type, $objects));
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
        )

)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.