doudengshen5591 2010-02-24 19:43
浏览 101
已采纳

优雅的方式将两个数组相互映射

I've got two arrays, one with IDs and one with Names:

$ids = array(4, 13, 6, 8, 10);
$names = array('alice', 'bob', 'charles', 'david', 'elizabeth');

I need to update the db so that the rows with the ids have the names in the array. Here's the tricky bit: I also have two ints:

$special_name = 2; // the index in $names, in this case we mean 'charles'
$special_id = 13;  // the id value

I don't care about which name goes to which id, except that the name with the $special_name should go on the $special_id.

What's the most elegant way to get there? All of the methods that I'm thinking of seem pretty messy. The best I've thought of is to extract out the special items from each array, and do those first, and then do the rest, perhaps building a new array like this:

$mapped = new array();
$mapped[$special_id] = $names[$special_name];
foreach ($ids as $id) {
    if ($id != $special_id) {
        $mapped[$id] = current($names);
    }
    // advance $names pointer
    $next_name = next($names);
    if ($next_name == $special_name) next($names);
}

I haven't tested that yet (I'm about to) but it's meant to produce something like:

$mapped = array(13=>'charles', 4=>'alice',6=>'bob', 8=>'david', 10=>'elizabeth');

and then running through that to do the actual update. Got a better idea?

UPDATE: added the possible solution above. Meanwhile a couple answers have come in.

  • 写回答

4条回答 默认 最新

  • duanca3415 2010-02-24 20:15
    关注

    If it wasn't for the special Ids, you could have just array_combine'd the two arrays. Here is how I think to have solved the issue:

    Setup

    $ids = array(4, 13, 6, 8, 10);
    $names = array('alice', 'bob', 'charles', 'david', 'elizabeth');
    $specialNameIndex = 2;
    $specialId = 13;
    

    Solution

      $result = array($specialId => $names[$specialNameIndex]);
      unset($ids[array_search($specialId, $ids)], 
            $names[$specialNameIndex]);
      $result += array_combine($ids, $names);
    

    Result

    print_r($result);
    Array
    (
        [13] => charles
        [4] => alice
        [6] => bob
        [8] => david
        [10] => elizabeth
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料