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
        )

)
\$\endgroup\$
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'])
        )
);
\$\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;
  }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.