dourangdz750379 2014-11-20 15:09
浏览 54
已采纳

比较数组中的差异并添加不存在的键

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条回答 默认 最新

  • doukuang1897 2014-11-20 15:14
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?