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

时间:2021-11-27 00:52:36

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”。有什么好办法呢?

9 个解决方案

#1


104  

You could use array_map() to do it.

您可以使用array_map()进行此操作。

$tags = array_map(function($tag) {
    return array(
        'name' => $tag['name'],
        'value' => $tag['url']
    );
}, $tags);

#2


18  

Loop through, set new key, unset old key.

循环,设置新键,未设置旧键。

foreach($tags as &$val){
    $val['value'] = $val['url'];
    unset($val['url']);
}

#3


7  

you can do something like this

你可以这样做

foreach($tags as &$tag){
    $tag['value'] = $tag['url'];
    unset($tag['url']);
}

#4


3  

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);
}

#5


2  

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的数量应该相同。但是当它们不是空键时,就会添加。这意味着您可以使用它将sort if模式添加到数组中。

Use this all the time, hope it helps!

一直使用这个,希望它能有所帮助!

#6


1  

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; 
}

#7


1  

foreach ($basearr as &$row)
{
    $row['value'] = $row['url'];
    unset( $row['url'] );
}

unset($row);

#8


0  

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);

#9


0  

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);

https://repl.it/@Piterden/Replace-keys-in-array

https://repl.it/@Piterden Replace-keys-in-array

#1


104  

You could use array_map() to do it.

您可以使用array_map()进行此操作。

$tags = array_map(function($tag) {
    return array(
        'name' => $tag['name'],
        'value' => $tag['url']
    );
}, $tags);

#2


18  

Loop through, set new key, unset old key.

循环,设置新键,未设置旧键。

foreach($tags as &$val){
    $val['value'] = $val['url'];
    unset($val['url']);
}

#3


7  

you can do something like this

你可以这样做

foreach($tags as &$tag){
    $tag['value'] = $tag['url'];
    unset($tag['url']);
}

#4


3  

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);
}

#5


2  

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的数量应该相同。但是当它们不是空键时,就会添加。这意味着您可以使用它将sort if模式添加到数组中。

Use this all the time, hope it helps!

一直使用这个,希望它能有所帮助!

#6


1  

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; 
}

#7


1  

foreach ($basearr as &$row)
{
    $row['value'] = $row['url'];
    unset( $row['url'] );
}

unset($row);

#8


0  

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);

#9


0  

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);

https://repl.it/@Piterden/Replace-keys-in-array

https://repl.it/@Piterden Replace-keys-in-array