如何在 PHP 中重命名数组键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9605143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to rename array keys in PHP?
提问by TK123
When I var_dump on a variable called $tags (a multidimensional array) I get this:
当我对一个名为 $tags(多维数组)的变量进行 var_dump 时,我得到了这个:
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 ) )
I would like to rename all array keys called "url" to be called "value". What would be a good way to do this?
我想将所有名为“url”的数组键重命名为“value”。这样做的好方法是什么?
回答by alex
You could use array_map()
to do it.
你可以array_map()
用来做。
$tags = array_map(function($tag) {
return array(
'name' => $tag['name'],
'value' => $tag['url']
);
}, $tags);
回答by Rocket Hazmat
Loop through, set new key, unset old key.
循环,设置新键,取消设置旧键。
foreach($tags as &$val){
$val['value'] = $val['url'];
unset($val['url']);
}
回答by CharybdeBE
Talking about functional PHP, I have this more generic answer:
谈到功能性 PHP,我有一个更通用的答案:
array_map(function($arr){
$ret = $arr;
$ret['value'] = $ret['url'];
unset($ret['url']);
return $ret;
}, $tag);
}
回答by Bill Barsch
Recursive php rename keys function:
递归php重命名键函数:
function replaceKeys($oldKey, $newKey, array $input){
$return = array();
foreach ($input as $key => $value) {
if ($key===$oldKey)
$key = $newKey;
if (is_array($value))
$value = replaceKeys( $oldKey, $newKey, $value);
$return[$key] = $value;
}
return $return;
}
回答by Stephen Fraser
This should work in most versions of PHP 4+. Array map using anonymous functions is not supported below 5.3.
这应该适用于大多数 PHP 4+ 版本。5.3 以下不支持使用匿名函数的数组映射。
Also the foreach examples will throw a warning when using strict PHP error handling.
当使用严格的 PHP 错误处理时,foreach 示例也会抛出警告。
Here is a small multi-dimensional key renaming function. It can also be used to process arrays to have the correct keys for integrity throughout your app. It will not throw any errors when a key does not exist.
这是一个小的多维键重命名函数。它还可以用于处理数组以在整个应用程序中拥有正确的完整性密钥。当键不存在时,它不会抛出任何错误。
function multi_rename_key(&$array, $old_keys, $new_keys)
{
if(!is_array($array)){
($array=="") ? $array=array() : false;
return $array;
}
foreach($array as &$arr){
if (is_array($old_keys))
{
foreach($new_keys as $k => $new_key)
{
(isset($old_keys[$k])) ? true : $old_keys[$k]=NULL;
$arr[$new_key] = (isset($arr[$old_keys[$k]]) ? $arr[$old_keys[$k]] : null);
unset($arr[$old_keys[$k]]);
}
}else{
$arr[$new_keys] = (isset($arr[$old_keys]) ? $arr[$old_keys] : null);
unset($arr[$old_keys]);
}
}
return $array;
}
Usage is simple. You can either change a single key like in your example:
用法很简单。您可以像示例中那样更改单个键:
multi_rename_key($tags, "url", "value");
or a more complex multikey
或更复杂的多键
multi_rename_key($tags, array("url","name"), array("value","title"));
It uses similar syntax as preg_replace() where the amount of $old_keys and $new_keys should be the same. However when they are not a blank key is added. This means you can use it to add a sort if schema to your array.
它使用与 preg_replace() 类似的语法,其中 $old_keys 和 $new_keys 的数量应该相同。但是,当它们不是空白键时会添加。这意味着您可以使用它向数组添加排序 if 模式。
Use this all the time, hope it helps!
一直在用,希望有帮助!
回答by Mr Griever
foreach ($basearr as &$row)
{
$row['value'] = $row['url'];
unset( $row['url'] );
}
unset($row);
回答by Alex
class DataHelper{
private static function __renameArrayKeysRecursive($map = [], &$array = [], $level = 0, &$storage = []) {
foreach ($map as $old => $new) {
$old = preg_replace('/([\.]{1}+)$/', '', trim($old));
if ($new) {
if (!is_array($new)) {
$array[$new] = $array[$old];
$storage[$level][$old] = $new;
unset($array[$old]);
} else {
if (isset($array[$old])) {
static::__renameArrayKeysRecursive($new, $array[$old], $level + 1, $storage);
} else if (isset($array[$storage[$level][$old]])) {
static::__renameArrayKeysRecursive($new, $array[$storage[$level][$old]], $level + 1, $storage);
}
}
}
}
}
/**
* Renames array keys. (add "." at the end of key in mapping array if you want rename multidimentional array key).
* @param type $map
* @param type $array
*/
public static function renameArrayKeys($map = [], &$array = [])
{
$storage = [];
static::__renameArrayKeysRecursive($map, $array, 0, $storage);
unset($storage);
}
}
Use:
用:
DataHelper::renameArrayKeys([
'a' => 'b',
'abc.' => [
'abcd' => 'dcba'
]
], $yourArray);
回答by Piterden
It is from duplicated question
它来自重复的问题
$json = '[
{"product_id":"63","product_batch":"BAtch1","product_quantity":"50","product_price":"200","discount":"0","net_price":"20000"},
{"product_id":"67","product_batch":"Batch2","product_quantity":"50","product_price":"200","discount":"0","net_price":"20000"}
]';
$array = json_decode($json, true);
$out = array_map(function ($product) {
return array_merge([
'price' => $product['product_price'],
'quantity' => $product['product_quantity'],
], array_flip(array_filter(array_flip($product), function ($value) {
return $value != 'product_price' && $value != 'product_quantity';
})));
}, $array);
var_dump($out);