如何在PHP中重命名子数组键?

78
当我使用var_dump在一个名为$tags的变量上(一个多维数组),我得到这个结果:
Array
(
    [0] => Array
        (
            [name] => tabbing
            [url] => tabbing
        )
[1] => Array ( [name] => tabby ridiman [url] => tabby-ridiman )
[2] => Array ( [name] => tables [url] => tables )
[3] => Array ( [name] => tabloids [url] => tabloids )
[4] => Array ( [name] => taco bell [url] => taco-bell )
[5] => Array ( [name] => tacos [url] => tacos ) )
我想将所有名为"url"的数组键重命名为"value"。有什么好的方法可以做到这一点?

请参考此SO帖子:https://dev59.com/RXVC5IYBdhLWcg3wnCaA - Bjoern
在 PHP >= 5.5.0 中,有 array_column 函数,可能对此非常有用。 - kenorb
14个回答

0

您可以不使用任何循环来完成

如下所示

$tags = str_replace("url", "value", json_encode($tags));  
$tags = json_decode($tags, true);
                    

不良实践。如果数组中的值包含字符串“url”,这也会更改数组的值。 - Kabelo2ka
是的,我知道,在那种情况下不要使用这个解决方案。 - Bhargav Variya

0
基于Alex提供的优秀解决方案,我根据我所处理的场景创建了一个更加灵活的解决方案。现在,您可以使用相同的函数处理具有不同嵌套键对数量的多个数组,只需传入一个用作替换的键名数组即可。
$data_arr = [
  0 => ['46894', 'SS'],
  1 => ['46855', 'AZ'],
];

function renameKeys(&$data_arr, $columnNames) {
  // change key names to be easier to work with.
  $data_arr = array_map(function($tag) use( $columnNames) {
    $tempArray = [];
    $foreachindex = 0;
    foreach ($tag as $key => $item) {
      $tempArray[$columnNames[$foreachindex]] = $item;
      $foreachindex++;
    }
    return $tempArray;
  }, $data_arr);

}

renameKeys($data_arr, ["STRATEGY_ID","DATA_SOURCE"]);

0

这对我来说完美地工作了

 $some_options = array();;
if( !empty( $some_options ) ) {
   foreach( $some_options as $theme_options_key => $theme_options_value ) {
      if (strpos( $theme_options_key,'abc') !== false) { //first we check if the value contain 
         $theme_options_new_key = str_replace( 'abc', 'xyz', $theme_options_key ); //if yes, we simply replace
         unset( $some_options[$theme_options_key] );
         $some_options[$theme_options_new_key] = $theme_options_value;
      }
   }
}
return  $some_options;

0

这是我如何重命名键,特别是对于已经在电子表格中上传的数据:

function changeKeys($array, $new_keys) {
    $newArray = [];

    foreach($array as $row) {
        $oldKeys = array_keys($row);
        $indexedRow = [];

        foreach($new_keys as $index => $newKey)
            $indexedRow[$newKey] = isset($oldKeys[$index]) ? $row[$oldKeys[$index]] : '';

        $newArray[] = $indexedRow;
    }

    return $newArray;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接