Compare differences in arrays and add non-existent keys

59 views Asked by At

Familiarization with the situation

Let's suppose we want to go trough the multidimensional array of error messages $errors with the following structure...

array(2) {
  // $id
  ["app_cannot_run"]=> array(2) {
    // $l
    ["ces"]=> string(36) "Webová aplikace nemůže být spuštěna."
    ["eng"]=> string(39) "The web application can not be started."
  }
  ["missing_file"]=> array(1) {
    ["ces"]=> string(32) "Požadovaný soubor nebyl nalezen."
  }
}

...and compare it with an array of published language versions:

$available_languages = array('ces','eng');

Also, there is a default language. This is primary and preferred language:

$default_language = 'ces';

Goal

All I need to do is find out if any error does not contain any language version except of the default one. I thought one way is work with function array_diff() or some ofshoot of this function. But at this time I have the following code with loops and I will appreciate any suggestion to do better:

foreach ($errors as $e => $id){
  foreach ($available_languages as $l){
    if (!array_key_exists($l,$id)){
        if ($l != $default_language){
          $alt_err_ver = $id[$default_language];
          $id[$l] = $alt_err_ver;
              /*
                 here comes a problem because I can save an alternative
                 language version of error into an array, but only for
                 an iteration (it's not going to printed after foreach loop).
              */
        }
    }
  }
}

print_r($errors);

The desired result:

array(2) {
  ["app_cannot_run"]=> array(2) {
    ["ces"]=> string(36) "Webová aplikace nemůže být spuštěna."
    ["eng"]=> string(39) "The web application can not be started."
  }
  ["missing_file"]=> array(2) {
    ["ces"]=> string(32) "Požadovaný soubor nebyl nalezen."
    ["eng"]=> string(32) "Požadovaný soubor nebyl nalezen."
  }
}

Sorry for my English, all who read it up to here thank you for your patience! ☺ Let me know if you do not understand some part of my question.

1

There are 1 answers

4
Aleksei Matiushkin On BEST ANSWER

array_map comes to the rescue:

$default_lang = 'ces';
$availables = array('ces','eng');

$result = array_map(function($el) use($default_lang, $availables) { 
  foreach($availables as $lang) {
    if(!array_key_exists($lang, $el)) { // no translation!
      $el[$lang] = $el[$default_lang];  // set to copy of default
    }
  }
  return $el; // return updated
}, $arr);

Hope this helps.