\$\begingroup\$
\$\endgroup\$
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
)
)
Emilio GortEmilio Gort
asked Feb 28, 2014 at 15:41
2 Answers 2
\$\begingroup\$
\$\endgroup\$
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
\$\begingroup\$
\$\endgroup\$
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
lang-php