1

I have to arrays that i want to join together without iterating them.
Backgroundinfo:

$Arr1 is an array of all Groups that a User is in.
$Arr2 is an array of all Contentpages associated to the Groups as the array key.

My aim is to get an array with all contentpages that the user is allowed to see

$Arr1 = array("Group1","Group3","Group5");

$Arr2["Group1"] = array("Content1","Content2");
$Arr2["Group2"] = array("Content5");
$Arr2["Group3"] = array("Content3");

My Result should be an array with all "Content" Elements:

array("Content1","Content2","Content3");  

Is there some trick with array_fill_keys or array_merge to avoid iterating?

1 Answer 1

3

You can try array_flip and array_intersect_key.

$intersect = array_intersect_key($Arr2, array_flip($Arr1))

Then you can flatten that into one array using array_merge.

$content = call_user_func_array('array_merge', $intersect);

DEMO: https://eval.in/430592

Sign up to request clarification or add additional context in comments.

2 Comments

+ I always preach PHP has an array function for every need. This is great proof of that.
Awesome thank you! Does somebody know how this will be on performance side - in comparision with a foreach loop?

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.