dsd30433 2017-04-20 18:21
浏览 79
已采纳

如何使用另一个数组值的子字符串对数组进行排序

I have something like a vocabulary list with every vocabulary containing a number and the word. I have the same list of vocabulary but unsorted and in another language, the numbers match the meaning. So the same word has in both languages the same number. How can I match both vocabularys together and being in the same order of the main language? Example:

Input:
English Array (sorted)    German Array (unsorted)
74 Apple                  6 Auto
6 car                     564 Zug       
564 train                 74 Apfel

Output: the German Array is sorted in the same way as the English Array

74 Apple                  74 Apfel
6 car                     6 Auto      
564 train                 564 Zug 

Help is much appreciated. Thank you :)

  • 写回答

1条回答

  • dongyou6795 2017-04-21 01:35
    关注

    Inputs:

    $english=["74 Apple","6 car","564 train"];
    $german=["6 Auto","564 Zug","74 Apfel"];
    

    First, create an array with keys in the desired order:

    array_map(function($v)use(&$sorting_keys){return $sorting_keys[substr($v,0,strpos($v,' '))]='';},$english);
    //var_export($sorting_keys);
    // array (
    //     74 => '',
    //     6 => '',
    //     564 => '',
    // )
    

    Next, reassign keys to the german array elements based on the leading id number

    array_map(function($v)use(&$keyed_german){return $keyed_german[substr($v,0,strpos($v,' '))]=$v;},$german);
    //var_export($keyed_german);
    // array (
    //     6 => '6 Auto',
    //     564 => '564 Zug',
    //     74 => '74 Apfel',
    // )
    

    Finally, transfer the values from $keyed_german to $sorting_keys (and reset the keys if you wish with array_values()):

    $sorted_german=array_values(array_replace($sorting_keys,$keyed_german));
    var_export($sorted_german);
    

    Output:

    array (
      0 => '74 Apfel',
      1 => '6 Auto',
      2 => '564 Zug',
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的