如何使用另一个关联数组重命名PHP数组中的某些键?

时间:2021-08-20 08:53:04

Given a data array ...

给定数据阵列......

$data_array = array (
"old_name_of_item" => "Item One!"
);

... and a rename array ...

...和重命名数组......

$rename_array = array (
"old_name_of_item" => "new_name_of_item"
);

... I would like to produce an output like this:

...我想生成这样的输出:

Array
(
    [new_name_of_item] => Item One!
)

I have written the following function, and while it works fine, I feel like I'm missing some features of PHP.

我编写了以下函数,虽然它工作正常,但我觉得我缺少PHP的一些功能。

function rename_keys($array, $rename_array) {
foreach( $array as $original_key => $value) {
    foreach( $rename_array as $key => $replace ) {
        if ($original_key == $key) {
            $array[$replace] = $value;
            unset($array[$original_key]); 
        }
    }
}
return $array;
}

Does PHP offer built-in functions to help with this common problem? Thanks!

PHP是否提供内置函数来帮助解决这个常见问题?谢谢!

2 个解决方案

#1


1  

You only have to go through the array once:

你只需要经历一次数组:

function rename_keys($array, $rename_array) {
    foreach ( $rename_array as $original_key => $value ) {
        if (isset($array[$original_key])) {
            $array[$rename_array[$original_key]] = $array[$original_key];
            unset($array[$original_key]);
        }
    }
}

This assumes, of course, that both arrays are correctly filled (unique values for the replacement keys).

当然,这假定两个数组都已正确填充(替换键的唯一值)。

Edit: only replace if a corresponding element exists in $rename_array.

编辑:仅在$ rename_array中存在相应元素时才替换。

Edit 2: only goes through $rename_array

编辑2:只通过$ rename_array

#2


0  

Second time today. This one is easier:

今天第二次。这个更容易:

$data_array = array_combine(
        str_replace(array_keys($rename_array), $rename_array, array_keys($data_array)), $data_array);

#1


1  

You only have to go through the array once:

你只需要经历一次数组:

function rename_keys($array, $rename_array) {
    foreach ( $rename_array as $original_key => $value ) {
        if (isset($array[$original_key])) {
            $array[$rename_array[$original_key]] = $array[$original_key];
            unset($array[$original_key]);
        }
    }
}

This assumes, of course, that both arrays are correctly filled (unique values for the replacement keys).

当然,这假定两个数组都已正确填充(替换键的唯一值)。

Edit: only replace if a corresponding element exists in $rename_array.

编辑:仅在$ rename_array中存在相应元素时才替换。

Edit 2: only goes through $rename_array

编辑2:只通过$ rename_array

#2


0  

Second time today. This one is easier:

今天第二次。这个更容易:

$data_array = array_combine(
        str_replace(array_keys($rename_array), $rename_array, array_keys($data_array)), $data_array);