更改数组的所有键

Changing all Keys of an Array

我有一个名为 $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)); 

如何正确更改密钥?

评论注:

Unfortunately, there will generally be more entries in $dictionary then $row and the order cannot be guaranteed

如果$dictionary可以翻转,那么

$dictionary = array_flip($dictionary);

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

如果没有,那么您最好进行手动循环。

我只想做一个手动循环并输出到一个新变量。 您不能使用 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);

 ?>

您的案例的解决方案中有几个潜在的 "gotcha"。由于您的两个数组可能大小不等,因此您必须在循环内使用 array_search() 。另外,虽然你的情况似乎不太可能,但我想提一下,如果 $dictionary 有键:"0"0 那么 array_search() 的 return必须严格检查 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',
)