【问题标题】:Changing all Keys of an Array更改数组的所有键
【发布时间】:2017-10-23 20:09:53
【问题描述】:

我有一个名为 $row 的数组:

$row = array(
    "comments" => "this is a test comment", 
    "current_path" => "testpath"
)

我还有另一个数组叫$dictionary

$dictionary= array(
    "comments" => "comments", 
    "current_directory" => "current_path"
)

我想将$row 中的键更改为与$dictionary 中的匹配值关联的键。

例如,在上述情况下,$row 将变为:

$row = array(
    "comments" => "this is a test comment", 
    "current_directory" => "testpath"
)

我尝试过使用array_map,但这似乎并没有改变任何东西:

array_map(function($key) use ($dictionary){
  return array_search($key, $dictionary);
}, array_keys($row)); 

如何正确更改密钥?

评论注释:

很遗憾,$dictionary 中的条目通常比 $row 多,并且无法保证顺序

【问题讨论】:

  • 字典可以倒置吗?
  • @tereško 很遗憾没有
  • @tereško 虽然我可以在$dictionary 的副本上使用array_flip 我想

标签: php arrays dictionary array-map


【解决方案1】:

您的案例的解决方案中有几个潜在的“陷阱”。由于您的两个数组的大小可能不相等,因此您必须在循环中使用array_search()。此外,尽管您的情况似乎不太可能,但我想提一下,如果$dictionary 有键:"0"0,则必须严格检查array_search() 的返回值是否为false。这是我推荐的方法:

输入:

$row=array(
    "comments"=>"this is a test comment", 
    "title"=>"title text",                      // key in $row not a value in $dictionary
    "current_path"=>"testpath"
);

$dictionary=array(
    "0"=>"title",                               // $dictionary key equals zero (falsey)
    "current_directory"=>"current_path",
    "comments"=>"comments", 
    "bogus2"=>"bogus2"                          // $dictionary value not a key in $row
);

方法(Demo):

foreach($row as $k=>$v){
    if(($newkey=array_search($k,$dictionary))!==false){  // if $newkey is not false
        $result[$newkey]=$v;                    // swap in new key
    }else{
        $result[$k]=$v;                         // no key swap, store unchanged element
    }
}
var_export($result);

输出:

array (
  'comments' => 'this is a test comment',
  0 => 'title text',
  'current_directory' => 'testpath',
)

【讨论】:

    【解决方案2】:

    我会做一个手动循环并输出到一个新变量。 您不能使用 array_map 或 array_walk 来更改数组的结构。

    <?php
       $row = ["comments" =>"test1", "current_path" => "testpath"];
    
       $dict = ["comments" => "comments", "current_directory" => "current_path"];
    
        foreach($row as $key => $value){
           $row2[array_search($key, $dict)] = $value;
       };
    
      var_dump($row2);
    
     ?>
    

    【讨论】:

      【解决方案3】:

      如果$dictionary可以翻转,那么

      $dictionary = array_flip($dictionary);
      
      $result = array_combine(
          array_map(function($key) use ($dictionary){ 
              return $dictionary[$key]; 
          }, array_keys($row)),
          $row
      );
      

      如果没有,那么你最好手动循环。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-30
        • 2021-02-12
        • 1970-01-01
        相关资源
        最近更新 更多