2
\$\begingroup\$

Is there a better way to do this kind of array combination with a PHP native function like array_combine? I'm trying to improve my skills, and at certain points I note that I am using too many nested foreach for almost everything.

Using PHP 5.4

 $array = Array(
 'GroupName' => 'Emilio',
 'Moduleid' => Array(
 0 => 15,
 1 => 12,
 2 => 9,
 3 => 1,
 4 => 11,
 5 => 10
 ),
 'Permission' => Array(
 15 => 'W',
 12 => 'R',
 14 => 'W',
 9 => 'W',
 1 => 'R',
 13 => 'W',
 11 => 'W',
 10 => 'R'
 )
 );
 foreach ($array['Moduleid'] as $value) {
 foreach ($array['Permission'] as $key1 => $value1) {
 if ($value == $key1) {
 $result[$key1] = $value1;
 }
 }
 }
 $newArray = array(
 'GroupName' => $array['GroupName'],
 'ModulePermission' => $result
 );
 unset($array);
 echo '<pre>';
 print_r($newArray);
 echo '</pre>';

Output

Array
(
 [GroupName] => Emilio
 [ModulePermission] => Array
 (
 [15] => W
 [12] => R
 [9] => W
 [1] => R
 [11] => W
 [10] => R
 )
)
asked Feb 28, 2014 at 15:41
\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

You can simplify this code considerably using the built-in array functions, specifically array_flip and array_intersect_key.

$newArray = array(
 'GroupName' => $array['GroupName'],
 'ModulePermission' => 
 array_intersect_key($array['Permission'], 
 array_flip($array['Moduleid'])
 )
);
answered Mar 1, 2014 at 1:53
\$\endgroup\$
3
\$\begingroup\$

Using in_array can be droped one foreach

$result = array();
foreach ($array['Permission'] as $key => $value) {
 if (in_array($key, $array['Moduleid'])) {
 $result[$key] = $value;
 }
}
answered Feb 28, 2014 at 16:30
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.